开发者

sed/awk: replace N occurrence

it's possible to change N (for example second occurrence) in file using one-line sed/awk exce开发者_如何学运维pt 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


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'


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜