从输出中 grep 特定变量并将值替换为另一个 linux

grep specific variable from output and replace value with another linux

我正在尝试使用以下命令获取 bash 中两个不同符号之间的变量名称:

nfs4_getfacl .| grep -E ":.:.*:"

这些是获得的字符串:

A:fdg:user@server:rxtTncC
A:g:user@server:xtcy
A:d:1111:xtcy

我正在尝试替换值 1111 或我在列表中遇到的任何其他数值,根据 nfs4 权限,这通常作为第三个位置出现,但情况并非总是如此:

1111 -> replaced_value

A:fdg:user@server:rxtTncC
A:g:user@server:xtcy
A:d:replaced_value:xtcy

使用您展示的示例,请输入以下内容。您可以在单个 awk 本身中执行此操作,我们不需要在此处使用 grep。根据您的需要设置 newValue 变量的值,然后它将相应地替换值。

nfs4_getfacl .| 
awk -v newValue="newVALUE" 'BEGIN{FS=OFS=":"} /:.:.*:/ && ~/^[0-9]+$/{=newValue} 1'

说明:为以上代码添加详细说明。

awk -v newValue="newVALUE" '  ##Getting nfs4_getfacl output as input to awk program, creating newValue variable which has new value in it.
BEGIN{ FS=OFS=":" }           ##Setting field separator and output field separator as : here.
/:.:.*:/ && ~/^[0-9]+$/{    ##Check if line contains :.:.*: format AND 3rd column is digits.
  =newValue                 ##Then set newValue value to 3rd column here.
}
1                             ##printing edited/non-edited lines here.
'