0

I have tried several awk arrays but just can´t get my head around it. Having a file with 4 colums the awk skript should count for each line how many times the value in column 2 appears.

Input File

A1^ABC^173^2012
A2^BDK^153^2013
A3^AFD^223^2012
B1^ABC^083^1999
B2^KLX^033^2012
B3^ABC^593^2003 
B4^KLX^323^2001

So as result I want to print the counter for the value in column 2 at the end of each line. E.g line one has value "ABC" in column2. "ABC" appears 3 times in the entire file and is printed at the end of the line.

Output File

A1^ABC^173^2012^3
A2^BDK^153^2013^1
A3^AFD^223^2012^1
B1^ABC^083^1999^3
B2^KLX^033^2012^2
B3^ABC^593^2003^3
B4^KLX^323^2001^2

Hope anyone got an idea on how to solve it.

Cheers

2 Answers 2

4

Here's one way using awk:

awk 'BEGIN { FS=OFS="^" } FNR==NR { a[$2]++; next } { print $0, a[$2] }' file.txt{,}

Results:

A1^ABC^173^2012^3
A2^BDK^153^2013^1
A3^AFD^223^2012^1
B1^ABC^083^1999^3
B2^KLX^033^2012^2
B3^ABC^593^2003^3
B4^KLX^323^2001^2
Sign up to request clarification or add additional context in comments.

7 Comments

What does the {,} do?
@Jotne Takes the input file twice, try echo file{,}.
Ahh, a new one for me, thanks :) -- {,,,} repeat it three times
@EdMorton: Thanks Ed; good question! Please see the 'portability' section here.
|
3

The buffered approach:

awk -F'^' -v OFS='^' '{a[NR]=$0;c[$2]++}
    END{for(i=1;i<=NR;i++){split(a[i],b);print a[i],c[b[2]]}}' file

Output:

A1^ABC^173^2012^3
A2^BDK^153^2013^1
A3^AFD^223^2012^1
B1^ABC^083^1999^3
B2^KLX^033^2012^2
B3^ABC^593^2003^3
B4^KLX^323^2001^2

To store the output in a new file use the redirection operator:

awk -F'^' -v OFS='^' '{a[NR]=$0;c[$2]++}
    END{for(i=1;i<=NR;i++){split(a[i],b);print a[i],c[b[2]]}}' file > outfile

2 Comments

+1 very good answer, trust me I hadn't seen this while making mine work.
works fine, many thanks. But I´m actually not getting the split and following print section. what is 'b' doing?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.