简体   繁体   中英

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.

How can I accomplish this?

I have tried various SED/AWK approaches, closest one is mentioned below:

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 . 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 .

Or by using 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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