gpt4 book ai didi

linux - 在 shell 脚本/SED/AWK 中搜索 A 并替换 A|B 中的 B

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:05:43 24 4
gpt4 key购买 nike

我有一个布局如下的文本文件:

tableName1|counterVariable1
tableName2|counterVariable2

我想用一些其他变量替换 counterVariable1,比如 counterVariableNew。

我怎样才能做到这一点?

我已经尝试过各种 SED/AWK 方法,最接近的方法如下所述:

cat $fileName | grep -w $tableName | sed -i 's/$tableName\|counterVariable/$tableName\|counterVariableNew'

但是这 3 个命令都没有正确合并,请帮忙!

最佳答案

您的脚本是 [ useless use of cat ] 的示例.但这里的关键点是在与 awk FS 一起使用时转义管道分隔符,它具有特殊含义(它代表 OR)。所以下面的脚本应该做

# cat 42000479
tableName1|counterVariable1
tableName2|counterVariable2
tableName3|counterVariable2

# awk -F\| '$1=="tableName2"{$2="counterVariableNew"}1' 42000479
tableName1|counterVariable1
tableName2 counterVariableNew
tableName3|counterVariable2

下面是做同样事情的另一种方法

# awk -v FS='|' '$1=="tableName2"{$2="counterVariableNew"}1' 42000479

单引号内的内容不会展开

关于linux - 在 shell 脚本/SED/AWK 中搜索 A 并替换 A|B 中的 B,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42000479/

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