Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add a number to a number located in a string in BASH

Tags:

bash

sql

parsing

I have a sql file that I need to modify so that the ID section of a row is increased by 3. How can I increased the ID field and keep the rest of the line as it is in BASH? Ex:

insert into info.names values (35, 'John', 'C', 2);
insert into info.names values (36, 'Mark', 'C', 1);
insert into info.names values (37, 'Bob', 'C', 5);

I need to add 3 to 35, 36 and 37, so that they become 38,39,40. SO the output would be

insert into info.names values (38, 'John', 'C', 2);
insert into info.names values (39, 'Mark', 'C', 1);
insert into info.names values (40, 'Bob', 'C', 5);

I'd like to do this in BASH.

Thank you

like image 665
JohnnyLoo Avatar asked Nov 19 '25 21:11

JohnnyLoo


1 Answers

awk is the more appropriate tool for this task

 awk '{tmp=$5 ;sub(/^\(/, "", tmp); tmp+=3; $5="("tmp","; print $0}' file > file.new && mv file.new file

To explain, I'll add comments and use a more verbose format

 awk '{  
       # Capture the 5th field '(35,' into a tmp variable
       tmp=$5                                    
       # remove the leading "(" char
       sub(/^\(/, "", tmp)
       # add 3 to the tmp value (see note below)
       tmp+=3
       # reconstruct the 5th field adding "(" and "," as needed.
       $5="(" tmp ","
       # print the whole line
       print $0
     }' file > file.new && mv file.new file
  #     |                  |-> if no error (`&&`) overwrite the original file 
  #     |                        with the fixed file (not an awk feature)
  #     |-> write output to tmp file                                                            

Note that after the operation sub(/^\(/, "", tmp) the value of tmp is actually 35, (note the , char!). When given a variable in a number context (like +=3 ) awk will only process only the number part of that value and then perform the math operation. That is why you get 38 and not 35,3. The line following then "put's back" the missing '(' and ',' chars.

IHTH

like image 187
shellter Avatar answered Nov 21 '25 10:11

shellter



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!