0

Highest Columns Number Records Issue

I have a test.txt file with contents as follows:

1:2:3
123:5
34589:5:0
34567:8:7
781:9:09

Could you please help me getting the following output from that test.txt file?

345895:0
345678:7
7819:09

Explanation: below line contains the highest number column i,g. 3 and removed :

345895:0
345678:7
7819:09
9
  • do u want to print if the first column is more than 3 digits?
    – Siva
    Sep 23 '19 at 12:37
  • records should be 2 column always. need to replace the those having more than 2 columns . thats it Sep 23 '19 at 12:40
  • @RabindraPanigrahi are you looking for something like: awk 'BEGIN{FS=OFS=":"} NR>=3 { print $1,$3 }' yourfile ? Sep 23 '19 at 12:42
  • 1:2:3 has 3 columns too, so shouldn't 12:3 appear in the output as well?
    – DonHolgo
    Sep 23 '19 at 12:43
  • Do you need to sort numbers by the first column and print the highest three? Why is the 781:9:09 converted to 7819:09? Do you compare numbers before this concatenation or after?
    – deimos
    Sep 23 '19 at 12:46
0

The solution is the following:

Assume that your file is called test.txt

cat test.txt | sort -nr | head -n 3 | sed 's/://'

Assume that the file content is the following:

1:2:3
123:5
34589:5:0
34567:8:7
781:9:09

The result will be the following:

345895:0
345678:7
781:9:09

Explaination


  • cat test.txt -> Simply print the content of the file to the stdout
  • sort -nr -> Sort the data assuming that are number symbol (-n), in reverse order (-r)
  • head -n3 -> Filter from the result, only the first 3 lines (-n 3)
  • sed 's/://' -> Remove the first : occurrence
0

Assuming I understood the requirements correctly, this should work:

awk 'BEGIN {FS=OFS=":"} NF > 2 {print $1$2,$3}' test.txt

This prints all lines with more than two columns, concatenating the first two into one.

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.