简体   繁体   English

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

[英]Search A and replace B in A|B in shell scripting/SED/AWK

I have a text file with layout as: 我有一个布局为的文本文件:

tableName1|counterVariable1
tableName2|counterVariable2

I want to replace the counterVariable1 with some other variable say counterVariableNew. 我想用其他变量counterVariableNew替换counterVariable1。

How can I accomplish this? 我该怎么做?

I have tried various SED/AWK approaches, closest one is mentioned below: 我已经尝试了多种SED / AWK方法,以下是最接近的一种:

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

But all the 3 commands are not merging properly, please help! 但是这三个命令都无法正确合并,请提供帮助!

Your script is an example of [ useless use of cat ] . 您的脚本是[猫的无用使用]的示例。 But the key point here is to escape the pipe delimiter which has a special meaning(it stands for OR) when used with awk FS . 但是关键是要避免与awk FS使用时具有特殊含义的管道定界符(代表OR)。 So below script should do 所以下面的脚本应该做

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

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

An alternate way of doing the same stuff is below 下面是做同样的事情的另一种方法

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

Stuff inside the single quote will not be expanded. 单引号内的内容将不会扩展。

awk -F'|' -v OFS='|' '/tableName1/ {$2="counterVariableNew"}1' file
tableName1|counterVariableNew
tableName2|counterVariable2

This will search for A (tableName1) and replace B (counterVariable1) to counterVariableNew . 这将搜索A (tableName1)并将B (counterVariable1)替换为counterVariableNew

Or by using sed : 或使用sed

sed -r '/tableName1/ s/(^.*\|)(.*)/\1counterVariableNew/g' file
tableName1|counterVariableNew
tableName2|counterVariable2

For word bounded search: Enclose the pattern inside \\< and \\> . 对于单词限制搜索:将模式括在\\<\\>

sed -r '/\<tableName1\>/ s/(^.*\|)(.*)/\1counterVariableNew/g' file
awk -F'|' -v OFS='|' '/\<tableName1\>/ {$2="counterVariableNew"}1' file

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM