gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 11:37:10 25 4
gpt4 key购买 nike

我有以下代码:

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 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 支持的正则表达式的信息。

关于linux - 仅当行以结果开头时 Awk 匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29065671/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com