簡體   English   中英

在文件中查找字符串並部分執行數學運算

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

我正在嘗試在文件中查找字符串,當我發現該字符串時,請將其分解並對其一部分進行數學運算。 聽起來sed無法使用,因為我想做數學運算,而awk會很困難,因為我想就地更新文件。

我的文件看起來像這樣(是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;
 }

我正在尋找@@行,並想在結尾@@之前的最后一個數字加1。 因此, @@ -3,5 +3,5 @@將變成@@ -3,5 +3,6 @@

您可以嘗試以下嗎?

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

如果您要將輸出保存到Input_file中,那么也可以在上述代碼中附加> temp_file && mv temp_file Input_file

注意:如果您使用的是GNU awk > = 4.1.0,則它中也確實有一個-i inplace

使用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