Dinesh B
Dinesh B

Reputation: 133

Replacing 14 character length of number in each line to a new number

I have a file with 45 character in each line.
Eg:

123456789123456789123456789123456789123456789

I need to cut the numbers between 10th to 15th character of each line and add the same with 1000. Now I need to place the result in same character lenght (say between 10th to 15th).

If 12345 is the 5 number between 10th to 15th character of a line, I need to add 1000 to it, so the value will be 13345.
So I need to replace the ans in the same location.

End result:

123456789133456789123456789

Please advice using unix.

Upvotes: 1

Views: 50

Answers (1)

whoan
whoan

Reputation: 8521

Here a way to accomplish it with Shell Parameter Expansion:

while read line; do
    echo "${line:0:9}$((${line:9:5} + 1000))${line:14}"
done < file

It just takes the relevant parts of the line and process them. It uses Substring Expansion:

${parameter:offset}
${parameter:offset:length}
Expands to up to length characters of parameter starting at the character specified by offset. If length is omitted, expands to the substring of parameter starting at the character specified by offset. length and offset are arithmetic expressions (see Shell Arithmetic). This is referred to as Substring Expansion.


Expanded to new requirements

Quoting:

I need to get the character values from 16th to 20th character of each line. I need to add 10000 to that number and place the result in two place in the same line, 1. from 16th to 20th character. 2. from 6th to 10th character.

eg:

i/p 1111122222333334444455555

o/p 1111154444333345444455555.

process: 16th to 20th character:44444

adding 10000: 54444(result)

(have to place this result in 2 location as mentioned above).

rest of the values in the lines should be as it is.

while read line; do
    A1=${line:0:5}
    #A2=${line:5:5}
    A3=${line:10:5}
    A4=${line:15:5}
    A5=${line:20}
    result=$((A4+10000))
    echo "$A1$result$A3$result$A5"
done < file

Explanation

It just saves the substrings from the line and then processes them accordingly:

1111122222333334444455555
<---><---><---><---><--->
 A1   A2   A3   A4   A5

Notice you don't need $A2, so, I've just commented it.
I hope it helps now.

Upvotes: 3

Related Questions