0

I have a file that looks like this

12;6
2;4
9;4
...

In this case the field (column) delimiter is a ";". I want to sort the fields in each line. An acceptable output would be:

6;12
2;4
4;9

An acceptable solution can assume that the field delimiter is a ";" and the values are integers. An ideal solution is more flexible, allowing different delimiters and for alphanumeric sorting.

This all needs to be done on the command line.

1
  • 1
    And what have you tried so far? Commented Oct 7, 2012 at 12:42

2 Answers 2

3
perl -wne '$,=";"; chop; 
    print sort { $a <=> $b } split ";";
    print "\n"' input

If your perl isn't ancient:

perl -wnE '$,=";"; chop; 
        say sort { $a <=> $b } split ";"' input

You can also do:

perl -F\; -wanE 'chop $F[-1]; $,=";"; say sort { $a <=> $b } @F' input
Sign up to request clarification or add additional context in comments.

1 Comment

The advantage of this solution (over some others) is that it works even if there a three or more fields on the line too.
2
 awk 'BEGIN{FS=OFS=";"}{if($1>$2)print $2,$1;else print $1,$2;}' file

test

kent$  cat t.txt
12;6
2;4
9;4
ccc;aaa
bab;baa

kent$  awk 'BEGIN{FS=OFS=";"}{if($1>$2)print $2,$1;else print $1,$2;}' t.txt
6;12
2;4
4;9
aaa;ccc
baa;bab

1 Comment

Why not -F';' on the command line, avoiding the verbose BEGIN block?

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.