仅当行以结果开始时,awk才匹配

时间:2015-03-15 20:13:52

标签: linux bash shell awk debian

我有以下代码:

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

我试图查看其他帖子,询问&#34; Awk行以&#34;比如这个,但是我无法理解它:

awk, print lines which start with four digits

1 个答案:

答案 0 :(得分:5)

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

相关问题