4

I have a file

1 4 2 1 2
1 1 2 4 5
1 2 4 5 9
2 3 4 5 1
1 0 2 1 5
2 2 2 1 1

sort -k1 file gives

1 0 2 1 5
1 1 2 4 5
1 2 4 5 9
1 4 2 1 2
2 2 2 1 1
2 3 4 5 1

I only want to first field to be sorted, others remains where they should be at, e.g. The sorted file should give:

1 4 2 1 2
1 1 2 4 5
1 2 4 5 9
1 0 2 1 5
2 3 4 5 1
2 2 2 1 1

Similarly sort -k1r testsort gives

2 3 4 5 1
2 2 2 1 1
1 4 2 1 2
1 2 4 5 9
1 1 2 4 5
1 0 2 1 5

When I want it to be

2 3 4 5 1
2 2 2 1 1
1 4 2 1 2
1 1 2 4 5
1 2 4 5 9
1 0 2 1 5

How can I do this in unix?

1 Answer 1

11

try this:

sort -s -n -k 1,1

This will work, and to learn more you can see here

3
  • Check this [ "$(echo -e "Mc Kevin\nsteffen" | sort -u | wc -l)" -eq 2 ] && echo The question owner is not steffen
    – steffen
    Commented Mar 6, 2014 at 9:39
  • thanks, I tried -s, but i missed out the 1,1 instead and did -k 1, what is the number after the , doing?
    – Mc Kevin
    Commented Mar 6, 2014 at 9:40
  • 1
    -kn,m: Sort by fields n-m (e. g. fields 1-4) where m defaults to end of line. If you sort from 1-1, only the first field is taken for comparison.
    – steffen
    Commented Mar 6, 2014 at 9:45

Your Answer

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

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