Monday, October 25, 2021

[SOLVED] How to replace a duplicate string with counter appended values in multiple files in linux command line

Issue

How can we modify the existing files by replacing a string "string" with counter incremented values as follows.

Note1: The first "string" is skipped. Note2: Also the "string" will not appear for more than one time in one line. Note 3: foo "string"bar -> foo "string"1bar is correct

File1 ("string" occurs once inside the file in any line)

some text
"string" here

File2 ("string" occurs thrice inside the file in any line)

some text
"string" here
some more
text "string"
why "string"

File3 ("string" does not occur inside the file in any line)

some text
why here
some more>
text pttn
why pttn

File4 ("string" occurs once inside the file in any line)

some "string"
no here

How can I replace the "string" with "string"1 "string"2, "string"3 etc?

Expected Output:

File1

some text
"string" here

File2

some text
"string"1 here
some more
text "string"2
why "string"3

File3

some text
why here
some more
text pttn
why pttn

File4

some "string"4
no here

Solution

Your question still isn't clear but this MAY be what you're looking for:

$ awk -v str='"string"' '
    BEGIN { lgth = length(str) }
    pos=index($0,str) {
        $0 = substr($0,1,pos+lgth-1) cnt substr($0,pos+lgth)
        cnt++
    }
    1' file{1,2,3,4}
some text
"string" here
some text
"string"1 here
some more
text "string"2
why "string"3
some text
why here
some more
text pttn
why pttn
some "string"4
no here

Just add -i inplace (with GNU awk) for it to change the input files instead of printing output. The above assumes you need a literal string match and that string doesn't need to be separated from other text by spaces, punctuition or anything else.



Answered By - Ed Morton