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

标签 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

我尝试查看其他询问“Awk 行开头为”的帖子,例如这篇文章,但我无法理解它:

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/

相关文章:

c - atexit()注册了多少个函数?

linux - 请帮忙为下面的场景编写unix脚本

linux - 节头列表指向哪个字符串表?

java - 使用 shell 脚本启动和终止 java 应用程序 (Debian)

java - 如何启动/停止/重新启动 Linux 服务以及如何从 Java 程序更新它们的配置文件

bash - 如何在 Bash 中使用带有长选项的 getopt?

linux - Bash 脚本解析 HTML 文件

bash - 如何比较 Bash 中 'if' 语句中的两个字符串变量?

git - 集中式 GIT 工作流/部署 - 发布分支

shell - 在 Rust 中使用 std::process::command 时找不到命令?