Sunday, May 8, 2011

Awk - replace n-th occurrence of pattern


Input file:
$ cat file.txt
FR 24
AA 33
EE 34
EE 46
BE 30
AA 31
DE 90
AL 10
AA 50
FR 67
EE 94
AA 80

Required:
Replace the "third" occurrence of first field "AA" with text "XX" in the above file.

Awk Solutions:
$ awk '$1=="AA" {
count++
if(count == 3){
sub("AA","XX",$1)
}
}
{print}' file.txt

Output:
FR 24
AA 33
EE 34
EE 46
BE 30
AA 31
DE 90
AL 10
XX 50
FR 67
EE 94
AA 80

In-case you want to add 100 to the 2nd field of that line where first field "AA" has occurred for the 3rd time, here is a way:
$ awk '$1=="AA" {
count++
if(count == 3){
$2=$2+100
}
}
{print}' file.txt

Output:
FR 24
AA 33
EE 34
EE 46
BE 30
AA 31
DE 90
AL 10
AA 150
FR 67
EE 94
AA 80

Related posts:
- Print up-to nth occurrence of a pattern in a file using awk
- Replace field other than the first occurrence using awk
- Awk print first occurrence of a set in a file

3 comments:

Malik said...

I have just started learning Unix. I found this website and it is very informative. It will help me to get some good concepts of Unix.
java tutorial

Akhil said...

Nice article.
Examples of Awk command in unix

Unknown said...

Required:
Replace the "third" occurrence of first field "AA" with text "XX"

perl -ple '/^AA(?{++$a})/ && $a == 3 && s//XX/' file.txt

> In-case you want to add 100 to the 2nd field of that line where first field "AA"
> has occurred for the 3rd time

perl -ple '/^AA(?{++$a})/ && $a == 3 && s/(\S+)$/$1+100/e' file.txt

© Jadu Saikia www.UNIXCL.com