Vitaliy
Vitaliy

Reputation: 359

sed/awk: replace N occurrence


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

Upvotes: 0

Views: 5523

Answers (2)

Fredrik Pihl
Fredrik Pihl

Reputation: 45644

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'

Upvotes: 8

Hai Vu
Hai Vu

Reputation: 40688

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

Upvotes: 2

Related Questions