Home > Software design >  awk sub count every 4 matches unlike every 1 match
awk sub count every 4 matches unlike every 1 match

Time:10-05

Let's say I have the following 1.txt file below:

    one file.txt
    two file.txt
    three file.txt
    
    four file.txt
    five file.txt
    sixt file.txt

    seven file.txt
    eight file.txt
    nine file.txt

I usually use the following command below to sequentially rename the files listed at 1.txt:

awk '/\.txt/{sub(".txt",  count"&")} 1' 1.txt > 2.txt

The output is 2.txt:

one file1.txt
two file2.txt
three file3.txt

four file4.txt
five file5.txt
sixt file6.txt

seven file7.txt
eight file8.txt
nine file9.txt

But I would like to rename only every 4 matches when the pattern is .txt.

to clarify, a pseudocode would be something like:

awk '/\.txt/{sub(".txt",  count"&")} 1 | <change every 4 matches> ' 1.txt > 3.txt

such that 3.txt is as below:

one file.txt
two file.txt
three file.txt

four file1.txt <-here
five file.txt
sixt file.txt

seven file.txt
eight file2.txt <- here
nine file.txt

I have been looking for both the web and in my learning and I do not remember something like that and I am having difficulty starting something to achieve this result.

Note: Maybe I just need to continue the command below:

awk -v n=0 '/\.txt/{if (n  ==4) sub(".txt",  count"&")} 1'

CodePudding user response:

You are almost there. Would you please try:

awk '/\.txt/ {if (  n%4==0) sub(".txt",  count"&")} 1' 1.txt > 2.txt

The condition n%4==0 meets every four valid lines.

  • Related