1

I have the following content in a file.

$ cat file.txt
path,foo,12344,bar,foo,example4/path/1,test2
path,bar,12345,bar,bar,example2/path/4,test5

I would like to change the "path" on the 6th field to "test-path".

path,foo,12344,bar,foo,example4/test-path/1,test2
path,bar,12345,bar,bar,example2/test-path/4,test5

I tried with following, but it didn't work.

$ awk -F, -v needle='path' -v replacement='test-path' 'BEGIN{ OFS = FS; } (NR > 1 && $6 == needle) { $6 = replacement; } 1' file.txt
6
  • @Prvt_Yadv Thanks for pointing out, I will add the filename.
    – smc
    Commented Mar 28, 2019 at 12:07
  • @Prvt_Yadv because there is an occurrence of the same string in 1st column, and I don't want to change that. I just want to change the 6th column content.
    – smc
    Commented Mar 28, 2019 at 12:09
  • Or you can assign full path instead of partial to variable.
    – Prvt_Yadav
    Commented Mar 28, 2019 at 12:09
  • @steeldriver I thought the same, I was not sure which one would do the regex part, thanks for pointing out ~, I will try the same.
    – smc
    Commented Mar 28, 2019 at 12:10
  • @steeldriver Unfortunately ~ didn't work. It is clear that I have to use regex to replace the part of the string in a column, but not sure about the exact way.
    – smc
    Commented Mar 28, 2019 at 12:18

2 Answers 2

3

Try this,

awk -F ',' -v OFS=',' '{gsub("path","test-path",$6)}1' file.txt

path,foo,12344,bar,foo,example4/test-path/1,test2
path,bar,12345,bar,bar,example2/test-path/4,test5

To substitute path with test-path only in 6th field

-1

Tried with below command

$ sed "s/\/path/\/test-path/" filename
path,foo,12344,bar,foo,example4/test-path/1,test2
path,bar,12345,bar,bar,example2/test-path/4,test
1
  • The risk here is that the sed command you've used would replace any and all "/path" strings to "/test-path" -- and not just the ones in field 6, as required.
    – Jeff Schaller
    Commented Mar 31, 2019 at 14:35

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .