如何使用grep捕获匹配?

问题描述:

我正在尝试编写一个脚本,用于增加在配置文件中找到的整数。我试图用grep找到当前值:如何使用grep捕获匹配?

$ grep versionNumber myfile.conf 
      versionNumber 123789 
^ whitespace 
     ^the key I need to match 
         ^the value I need to capture 

我期望的结果是捕捉示例中的123789以上。

我需要做什么才能捕捉到这个值?

+0

你所说的 “捕捉” 意思?你的意思是“印刷”还是别的什么?根据您发布的输入文件,您希望编写的脚本的输出结果是什么? –

你可以这样做:

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 

使用awk

awk '/versionNumber/{print $2}' myfile.conf 
+1

好的,免去了使用'grep'的需要 – anubhava

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