0

I have a file that looks like this:

"string",192.168.1.0,,TX,192.168.1.2,,,100,0,0,10,10,10,,
"string",192.168.1.0,,TX,192.168.1.1,,,100,0,0,10,10,10,,
"string",192.168.1.0,,TX,192.168.1.4,,,100,0,0,10,10,10,,
"string",192.168.1.0,,TX,192.168.1.2,,,100,0,0,10,10,10,,

With this command I expect it to pull the second ip address, and basically list how many times that IP is listed in this file.

cat originalFile.txt | awk -F "," '{print $5}' | sort | uniq -c > outputFile.txt

This sorts incorrectly. I want the output file to look like below (organized by the first column)

1 192.168.1.1
1 192.168.1.4
2 192.168.1.2

I've tried changing the sort section to

sort -n -k1

I think the problem is that i'm sorting before it's performing uniq, but any other order seems to break the process. Right now my fix is to just run two commands like this.

    cat originalFile.txt | awk -F "," '{print $5}' | sort | uniq -c > outputFile1.txt
    sort -n -k1 outputFile1.txt > outputFile2.txt

Obviously using a temporary file for this isn't ideal, and I'm sure I just need to slightly modify this and put it in a different order. Any help is appreciated.

  • uniq -c will sort by the items themselves, not the count. If you want to sort by the count, you'll need to pipe the output to sort one more time. – ernie Aug 8 '14 at 16:14
1

Sort for the uniq, then later sort for the final order:

cat originalFile.txt | awk -F "," '{print $5}' | sort | uniq -c | sort -n

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.