简体   繁体   English

在文件中查找字符串并部分执行数学运算

[英]Find string in file and perform math on part in Linux

I'm trying to find a string in a file, and when I find that string break it up and perform math on part of it. 我正在尝试在文件中查找字符串,当我发现该字符串时,请将其分解并对其一部分进行数学运算。 It sounds like sed won't work because I want to do math and awk will be difficult because I want to update the file in place. 听起来sed无法使用,因为我想做数学运算,而awk会很困难,因为我想就地更新文件。

My file looks like this (is an svn diff) 我的文件看起来像这样(是svn diff)

Index: code/foo.c
===================================================================
--- code/foo.c  (revision 13)
+++ code/foo.c  (working copy)
@@ -3,5 +3,5 @@
 int main(int argc, char *argv[])
 {
     printf("I don't like being moved around!\n%s", bar());
-    return 0;
+    return 1;
 }

I'm looking for the @@ line and want to add 1 to the last number before the ending @@ . 我正在寻找@@行,并想在结尾@@之前的最后一个数字加1。 So, @@ -3,5 +3,5 @@ would become @@ -3,5 +3,6 @@ 因此, @@ -3,5 +3,5 @@将变成@@ -3,5 +3,6 @@

Could you please try following. 您可以尝试以下吗?

awk '
BEGIN{
  FS=OFS=","
}
/^@@.*@@/{
  split($NF,array," ")
  $NF=array[1]+1" " array[2]
}
1
'   Input_file

In case in you want to save output into Input_file then append > temp_file && mv temp_file Input_file in above code too. 如果您要将输出保存到Input_file中,那么也可以在上述代码中附加> temp_file && mv temp_file Input_file

NOTE: In case you are using GNU awk >= 4.1.0 does have an -i inplace in it too. 注意:如果您使用的是GNU awk > = 4.1.0,则它中也确实有一个-i inplace

With GNU awk for the 3rd arg to match(): 使用GNU awk作为第三个参数match():

$ awk 'match($0,/^(@@.*,)([0-9]+)( @@)$/,a){$0=a[1] a[2]+1 a[3]} 1' file
Index: code/foo.c
===================================================================
--- code/foo.c  (revision 13)
+++ code/foo.c  (working copy)
@@ -3,5 +3,6 @@
 int main(int argc, char *argv[])
 {
     printf("I don't like being moved around!\n%s", bar());
-    return 0;
+    return 1;
 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM