0

My text file consist of 5 columns. Based on the user input want to search only in 2nd, 3rd, 4th and 5th column and replace it.

for example

oldstring="Old_word" 
newstring="New_word"

So want to find all the exact match of oldstring and replace the same with newstring. Column one should be untouched even if there is a match.

Browsed and found that awk will do but I am able to change in one particular column.

bash script

Nike
  • 33
  • 7
  • add couple of sample input line and expected output for that.. it would help for testing purposes as well as help in understanding the question better... here's an example of looping over input fields: https://stackoverflow.com/questions/6997430/looping-over-input-fields-as-array please try something yourself and add to question – Sundeep May 03 '18 at 15:54
  • here's an example for changing specific field based on a condition - https://stackoverflow.com/a/23834095 – Sundeep May 03 '18 at 15:57

2 Answers2

1
$ cat testfile
a,b,c Old_word,d,e
f,gOld_wordOld_wordOld_words,h,i,j

$ awk -F, -v OFS=, -v oldstring="Old_word" -v newstring="New_Word" '{
    for (i=2; i<=5; i++) { gsub(oldstring,newstring,$i) }
    print
}' testfile
a,b,c New_Word,d,e
f,gNew_WordNew_WordNew_Words,h,i,j

For more information about read the awk info page

glenn jackman
  • 238,783
  • 38
  • 220
  • 352
1

Another way, similar to Glenn Jackman's answer is :

$ awk -F, -v OFS=, -v old="Old_word" -v new="New_word" '{
      s=$1; $1=""; gsub(old,new,$0); $1=s
      print }' <file>
kvantour
  • 25,269
  • 4
  • 47
  • 72