Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enumerate substitutions with sed or awk

Given the plain text file with lines

bli foo bla
 abc
 dfg
bli foo bla
 hik
 lmn

what sed or awk magic transforms it to

bli foo_01 bla
 abc
 dfg
bli foo_02 bla
 hik
 lmn

so that every occurence of 'foo' is replaced by 'foo_[occurence number]'.

like image 681
Michael Locher Avatar asked Sep 14 '25 10:09

Michael Locher


1 Answers

awk '!/foo/||sub(/foo/,"&_"++_)' infile

Use gawk, nawk or /usr/xpg4/bin/awk on Solaris.

like image 171
Dimitre Radoulov Avatar answered Sep 16 '25 03:09

Dimitre Radoulov