将数字添加到BASH中字符串中的数字

时间:2015-05-20 20:02:38

标签: sql bash parsing

我有一个我需要修改的sql文件,以便行的ID部分增加3.如何增加ID字段并保留BASH中的其余部分? 例如:

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);

我需要加3到35,36和37,这样它们就变成了38,39,40。那么输出就是

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);

我想在BASH中这样做。

谢谢

3 个答案:

答案 0 :(得分:2)

使用gnu-awk你可以这样做:

awk 'BEGIN{ FPAT="[^(]+|\\([0-9]+" } {$2="(" substr($2,2)+3} 1' file.sql
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);

答案 1 :(得分:2)

awk是更适合此任务的工具

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

为了解释,我将添加评论并使用更详细的格式

 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                                                            

请注意,在操作sub(/^\(/, "", tmp)之后,tmp的值实际为35,(请注意, char!)。当在数字上下文中给出变量时(如+=3),awk将仅处理该值的数字部分,然后执行数学运算。这就是为什么你得到38而不是35,3。接下来的行“放回”丢失的'('和','字符。

IHTH

答案 2 :(得分:0)

谢谢。我不是一个awk guru,所以有些事我不明白。这就是我所做的,但肯定比你所有的答案都要麻烦。

sed -n -r 's/^insert .*\(([0-9]+),.*;/\1/p' Names.sql | while read line; do grep "^insert into info.names values ($line," Names.sql | while read SQLLine; do OLDID=$(echo "$SQLLine" | sed -n -r 's/^insert .*\(([0-9]+),.*;/\1/p'); NEWID=$(expr 2 + $OLDID); sed -n -r "s/(insert into info.names values \()[0-9]+(, .*)/\1$NEWID\2/p" <(echo "$SQLLine"); done; done

谢谢你们

相关问题