Using Raku (formerly known as Perl_6)
~$ raku -ne 'BEGIN my %hash; put /^tag\:/ && %hash{$_}++ ?? $_ ~ sprintf("-%02d", %hash{$_}-1) !! $_;' file
Above is the Raku version of an excellent awk
answer posted by @EdMorton in a comment.
Start by calling Raku at the commandline with the -ne
non-autoprinting linewise flags. Before entering the linewise code BEGIN
by declaring a %hash
. Run the put
... statement over the input. If the line /^tag:/
starts with tag:
add the line to the %hash
and ++
increment its value.
This &&
conditional forms the beginning of Raku's "Test ??
True !!
False" ternary operator. If True, the $_
line is output
with the line's value minus one appended (value decoded using %hash{$_}
). If False, the line is output
unchanged.
Sample Input:
tag:20230901-FAT
val:1034
tag:20230901-FAT
val:1500
tag:20230901-LAX
val:8934
tag:20230901-SMF
val:2954
tag:20230901-LAX
val:1000
tag:20230901-FAT
val:1500
Sample Output:
tag:20230901-FAT
val:1034
tag:20230901-FAT-01
val:1500
tag:20230901-LAX
val:8934
tag:20230901-SMF
val:2954
tag:20230901-LAX-01
val:1000
tag:20230901-FAT-02
val:1500
Above implements a count-up suffix, leaving the earliest tag:
lines unchanged. To implement a count-down suffix that leaves the final tag:
lines unchanged, use tac
twice as instructed in the accepted answer by @FelixJN. Below, the answer implemented on MacOS which uses tail -r
instead of tac
:
~$ tail -r Steve_suffix.txt | raku -ne 'BEGIN my %hash; put /^tag:/ && %hash{$_}++ ?? $_ ~ sprintf("-%02d", %hash{$_}-1) !! $_;' | tail -r
tag:20230901-FAT-02
val:1034
tag:20230901-FAT-01
val:1500
tag:20230901-LAX-01
val:8934
tag:20230901-SMF
val:2954
tag:20230901-LAX
val:1000
tag:20230901-FAT
val:1500
https://unix.stackexchange.com/a/114043
https://docs.raku.org/language/operators#infix_??_!!
https://raku.org