0

I have a text file, and would like to append a counter to a number of different strings of interest. An example infile:

string_of_interest
abcd
efgh
another_string_of_interest
ijkl
abcd
another_string_of_interest
mnop
wxyz
string_of_interest
ijkl
wxyz
another_good_string
abcd
efgh
another_string_of_interest

As you can see there are multiple strings to ignore, some of which might repeat, but I only want to count repeats for a subset of strings to produce an outfile like this:

string_of_interest_1
abcd
efgh
another_string_of_interest_1
ijkl
abcd
another_string_of_interest_2
mnop
wxyz
string_of_interest_2
ijkl
wxyz
another_good_string_1
abcd
efgh
another_string_of_interest_3

Note the counter is appended as part of each string using snake case.

I've fumbled around with sed and awk to try, but I'm so novice I'm nowhere close yet. Any recommendations?

3
  • 1
    sed is notoriously bad at counting, you you probably want to use awk or some other language with support for arithmetics.
    – Kusalananda
    Commented Apr 29, 2021 at 6:57
  • Could you ever have two strings of interest, A and A_1 (or A_n, for some positive integer n)?
    – Kusalananda
    Commented Apr 29, 2021 at 7:14
  • Please read how-do-i-find-the-text-that-matches-a-pattern to understand why this matters and then edit your question to include a target string that contains regexp metachars and is a substring of other strings in your input so we can see how those should be handled. For example use t.*e as the "string" and include lines with the and at.*en in your input as well as the real target string foo_t.*e_bar.
    – Ed Morton
    Commented Apr 29, 2021 at 14:00

1 Answer 1

3

if all those line with your interested string contains a key string like "string", you could do:

awk '/string/{ $0=$0 "_" ++seen[$0] }1' infile

otherwise use below code, that is for each line that matches the corresponding string of interest appends an incrementing counter for it.

awk '
    $0 == "string_of_interest" ||
    $0 == "another_string_of_interest" ||
    $0 == "another_good_string" { $0=$0 "_" ++seen[$0] } 1
' infile
0

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .