1

This question already has an answer here:

How can we search and replace "xyz" in col3 only?

col1,col2,col3,col4  
abc,def,xyz,xyz  
xyz,abc,def,xyz

marked as duplicate by Sundeep, Romeo Ninov, Kusalananda, Jeff Schaller, Thomas Jul 9 '18 at 12:19

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

3

Try this:

awk -F , '{ if ($3 == "xyz") $3="abc";}1' OFS=, test.csv
0

You didn't mention what you want to replace it with so I'm just going to use ghi as a placeholder:

If that is the actual text then the easiest way is with sed. You can do it with awk but that will only send the modification to standard output whereas sed can change the file itself which is explained below:

sed '2s|xyz|ghi|1' file

To explain:

2s replaces instances on the second line
xyz is what you want to replace
ghi is what it's being replaced with
1 replaces the first instance of it on the specified line

The output:

col1,col2,col3,col4
abc,def,ghi,xyz
xyz,abc,def,xyz

Once you're sure that it does what you want, use the -i switch to change the file itself instead of sending it to standard output:

sed -i '2s|xyz|ghi|1' file

If there are other lines and columns where you might want to replace it, you'll need to modify 2s and 1 to specify the location(s) and instance(s). Obviously, you'd also replace ghi with whatever replacement you'd like.

If there are other lines in column 3 where you need to replace xyz, you can use the e switch. For example:

col1,col2,col3,col4
abc,def,xyz,xyz
xyz,abc,def,xyz
abc,def,xyz,abc

xyz appears in the fourth line of column 3 as well.

sed -e '2s|xyz|ghi|1' -e '4s|xyz|ghi|1' file

sed -i -e '2s|xyz|ghi|1' -e '4s|xyz|ghi|1' file

That would replace the first instance on the fourth line as well using -e to specify each stream of replacements. The -i switch changes the file instead of only sending it to standard input.

0
awk -F ',' -v needle='xyz' -v replacement='foobar' 'BEGIN{ OFS = FS; } (NR > 1 && $3 == needle) { $3 = replacement; } 1' input.txt

Set needle and replacement as required. NR > 1 ensures that no replacement happens in the first row (apparently containing the column headers).

Not the answer you're looking for? Browse other questions tagged or ask your own question.