0

I need to search files in directory with specific pattern (for example foobar) and replace them with foobarXXX, where XXX is a number. For example, there were two original file

snt130.txt

My mistress' eyes are nothing like foobar;
foobar is far more red than her lips' red;

snt18.txt

Shall I compare thee to a summer's day?
Thou art more lovely and more foobar:

After proccessing I need something like this (order of numbers does not matter, just uniqueness)

snt130.txt

My mistress' eyes are nothing like foobar001;
foobar002 is far more red than her lips' red;

snt18.txt

Shall I compare thee to a summer's day?
Thou art more lovely and more foobar003:

What is the simplest way to perform this search&replace task (preferably with bash)

  • How do we determine the order of files? That snt130 should be done first and snt18 next? Can it be in any order – Inian Nov 3 '17 at 11:52
  • "order of numbers does not matter, just uniqueness" – Loom Nov 3 '17 at 11:55
  • Bash isn’t much of a text editor... – Jeff Schaller Nov 3 '17 at 12:10
  • I would suggest an accurate python solution – RomanPerekhrest Nov 3 '17 at 18:57
  • @RomanPerekhrest - Python solution is interesting too – Loom Nov 3 '17 at 18:59
1
$ cat f1
My mistress' eyes are nothing like foobar;
foobar is far more red than her lips' red;
$ cat f2
Shall I compare thee to a summer's day?
Thou art more lovely and more foobar:

With perl

$ perl -i -pe 's/foobar\K/sprintf "%03d", ++$i/ge' f1 f2
$ cat f1
My mistress' eyes are nothing like foobar001;
foobar002 is far more red than her lips' red;
$ cat f2
Shall I compare thee to a summer's day?
Thou art more lovely and more foobar003:
  • default value of uninitialized variable is 0 in numeric context
  • e modifier allows to use Perl code in replacement section
  • foobar\K string to replace, \K used just as a convenience here


With gawk having inplace extension and assuming only one instance of string per line

gawk -i inplace -v s='foobar' '$0 ~ s{sub(s, sprintf("%s%03d", s, ++i))} 1' f1 f2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.