简体   繁体   中英

How to use awk to print counter+1 if line does not match previous line

I have been working in bash trying print text based on an input file. My file contains the following text:

a
a
a
b
c
c
c
d
d
e
e

For each line that does not match the previous line, I want to add 1 to a counter and print the counter next to original entry. For lines that are equal, I would like to print the counter as is, like so:

a 1  
a 1  
a 1  
b 2  
c 3  
c 3  
c 3  
d 4  
d 4  
e 5  
e 5   

I have tried the code below, but this only provides me with information for the lines that are equal to the previous lines and does not print the counter.

f=a
counter=1

awk '{ 
if ($0==f && NR>1) {print f, counter} {f=$0} ; 
next
elif ($0!=f && NR>1) 
{print f, ++counter} {f=$0}
}' file.txt

output:

a   
a   
c   
c   
d   
e   

This is all you need

awk '
    $1 != prev {c++; prev=$1} 
    {print $0, c}
' file

On the first line of the file, both prev and c will be undefined. The $1 != prev test will be true. awk will treat undefined c as the number zero in arithmetic context, so the ++ operator properly sets c to 1.

Two place you're going wrong:

  • expecting to be able to share shell and awk variables. You can't that way
  • syntax for the if command: you have way too many braces.

This is your code restructured so that it works:

awk -v f=a -v counter=1 '{
    if ($0==f && NR>1) {print f, counter; f=$0 ; next}
    if ($0!=f && NR>1) {print f, ++counter; f=$0}
}' file

But it's written in a non-idiomatic way, and is pretty repetitive. Plus you need to know the first line of the file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM