仅当行以结果开头时 Awk 匹配

Awk match only when line starts with result

我有以下代码:

function replaceappend() {
    awk -v old="" -v new="" '
        sub(old,new) { replaced=1 }
        { print }
        END { if (!replaced) print new }
    ' "" > /tmp/tmp$$ &&
    mv /tmp/tmp$$ ""
}

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 line starting with" 的帖子,例如这个,但我无法理解它:

awk, print lines which start with four digits

在正则表达式中,^只匹配行首。因此,要仅在行首匹配 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 支持的正则表达式的信息。