• Uncategorized

About linux : Sed-String-manipulation

Question Detail

I need help
From a list I would like to get the addition of characters like the example below:
Start:

1
1
13
5
14
4
1
5
12
7
8
9
4
18
3
20
11
17
13

===============================================
Final results :

9001
9001
9013
9005
9014
9004
9001
9005
9012
9007
9008
9009
9004
9018
9003
9020
9011
9017
9013

this command does not work:

sed "s/^/9000/g" file.txt

Question Answer

This might work for you (GNU sed):

sed -r 's/^/0000/;s/^0*(.{3})$/9\1/' file

Prepend zeroes to the front of the number. Prepend a 9 and remove excess zeroes.

This should work for you.

for num in `cat file.txt`; do if [ $num -le 9000 ]; then echo "$(($num + 9000))"; else echo $num; fi; done

You can do it like this:

 for num in 1 1 13 5 14 4 1 5 12 7 8 9 4 18 3 20 11 17; do echo "$(($num + 9000))"; done

If you also have numbers in the list, which you don’t want to process, because they are already in the 90XX format you can throw in an if statement:

for num in 1 1 13 5 14 4 1 5 12 7 8 9 4 18 3 20 11 17 9005; do if [ $(($num)) -le 9000 ]; then echo "$(($num + 9000))"; else echo $num; fi; done

For loop in bash – for; do; done;

Bash arithmetic expression to add the numbers – $((EXPR))

You can try (GNU sed):

sed 's/.*/echo $((9000+&))/e' infile

You may also like...

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.