0


it's possible to change N (for example second occurrence) in file using one-line sed/awk except such method?:

line_num=`awk '/WHAT_TO_CHANGE/ {c++; if (c>=2) {c=NR;exit}}END {print c}' INPUT_FILE` && sed  "$line_num,$ s/WHAT_TO_CHANGE/REPLACE_TO/g" INPUT_FILE > OUTPUT_FILE


Thanks

makerofthings7
  • 60,103
  • 53
  • 215
  • 448
Vitaliy
  • 359
  • 1
  • 7
  • 16

2 Answers2

8

To change the Nth occurence in a line you can use this:

$ echo foo bar foo bar foo bar foo bar | sed 's/foo/FOO/2'
foo bar FOO bar foo bar foo bar

So all you have to do is to create a "one-liner" of your text, e.g. using tr

tr '\n' ';'

do your replacement and then convert it back to a multiline again using

tr ';' '\n'
Fredrik Pihl
  • 44,604
  • 7
  • 83
  • 130
2

This awk solution assumes that WHAT_TO_CHANGE occurs only once per line. The following replaces the second 'one' with 'TWO':

awk -v n=2 '/one/ { if (++count == n) sub(/one/, "TWO"); } 1' file.txt
Hai Vu
  • 37,849
  • 11
  • 66
  • 93