我正在嘗試編寫一個腳本,用於增加在配置文件中找到的整數。我試圖用grep
找到當前值:如何使用grep捕獲匹配?
$ grep versionNumber myfile.conf
versionNumber 123789
^ whitespace
^the key I need to match
^the value I need to capture
我期望的結果是捕捉示例中的123789
以上。
我需要做什麼才能捕捉到這個值?
我正在嘗試編寫一個腳本,用於增加在配置文件中找到的整數。我試圖用grep
找到當前值:如何使用grep捕獲匹配?
$ grep versionNumber myfile.conf
versionNumber 123789
^ whitespace
^the key I need to match
^the value I need to capture
我期望的結果是捕捉示例中的123789
以上。
我需要做什麼才能捕捉到這個值?
你可以這樣做:
grep versionNumber myfile.conf | grep -oE '[0-9]+'
或本
grep versionNumber myfile.conf | awk '{print $2}'
或本
grep versionNumber myfile.conf | cut -d' ' -f2
,或者如果你有GNU的grep與爲-P
模式支持:
grep -oP 'versionNumber \K\d+' myfile.conf
使用grep -oP
(PCRE模式);
s=' versionNumber 123789'
grep -oP 'versionNumber\h+\K\S+' <<< "$s"
123789
腳本,增加使用了GNU AWK V A配置文件發現了一個整數4.1.0+:
測試文件:
$ cat > file
foo
versionNumber 123789
bar
使用就地編輯功能:
$ awk -i inplace '/versionNumber/ {n=index($0,"v"); sub($2,$2+1); printf "%-"n"s\n", $0; next} 1' file
結果:
$ cat file
foo
versionNumber 123790
bar
說明:
鍵編輯文件就地是-i inplace
/versionNumber/ { # if versionNumber found in record
n=index($0,"v") # count leading space amount to n
sub($2,$2+1) # increment the number in second field
printf "%-"n"s\n", $0 # print n space before the (trimmed) record
next # skip print in the next line
} 1 # print all other records as were
你所說的 「捕捉」 意思?你的意思是「印刷」還是別的什麼?根據您發佈的輸入文件,您希望編寫的腳本的輸出結果是什麼? –