简体   繁体   中英

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.

My file looks like this (is an 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 @@ . So, @@ -3,5 +3,5 @@ would become @@ -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.

NOTE: In case you are using GNU awk >= 4.1.0 does have an -i inplace in it too.

With GNU awk for the 3rd arg to 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;
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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