我有以下代码:
function replaceappend() {
awk -v old="$2" -v new="$3" '
sub(old,new) { replaced=1 }
{ print }
END { if (!replaced) print new }
' "$1" > /tmp/tmp$$ &&
mv /tmp/tmp$$ "$1"
}
replaceappend "/etc/ssh/sshd_config" "Port" "Port 222"
它工作得很好,但我希望对其进行修改,以便 awk 命令仅在该行以该结果开头时才找到匹配项。因此,如果它正在寻找单词“Port”:
Port 123 # Test <- It would match this one
This is a Port <- It would not match this one
我尝试查看其他询问“Awk 行开头为”的帖子,例如这篇文章,但我无法理解它:
最佳答案
在正则表达式中,^
仅匹配行的开头。因此,要仅在行的开头匹配 Port
,请编写 ^Port
。
例如,让我们创建一个文件;
$ cat >testfile
Port 123 # Test <- It would match this one
This is a Port <- It would not match this one
应用你的函数:
$ replaceappend testfile ^Port REPLACED
结果:
$ cat testfile
REPLACED 123 # Test <- It would match this one
This is a Port <- It would not match this one
GNU documentation有关 GNU awk 支持的正则表达式的更多信息。
关于linux - awk 仅当行以结果开头时才匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29065671/