7beggars_nnnnm
7beggars_nnnnm

Reputation: 777

awk sub ++count every 4 matches unlike every 1 match

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'

Upvotes: 0

Views: 106

Answers (3)

The fourth bird
The fourth bird

Reputation: 163642

Another option could be passing n=4 to use it for both the modulo and the division.

For the string you could pass s=".txt" for index() to check if it present and for sub to use in the replacement.

awk -v str=".txt" -v nr=4 'index($0,str){if(!(++i%nr)) sub(str,i/nr"&")}1' 1.txt > 2.txt

Upvotes: 1

RavinderSingh13
RavinderSingh13

Reputation: 133780

Adding 1 more awk variant here, based on your shown samples only. Simple explanation would be, check if line is NOT NULL AND count variable value is 4, then substitute .txt with count1(increasing with 1 each time) with .txt itself and print the line.

awk 'NF && ++count==4{sub(/\.txt/,++count1"&");count=0} 1' 1.txt > 2.txt

Upvotes: 4

tshiono
tshiono

Reputation: 22087

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.

Upvotes: 3

Related Questions