43

I want to do something like this:

cat abcd.txt | cut -f 2,1 

and I want the order to be 2 and then 1 in the output. On the machine I am testing (FreeBSD 6), this is not happening (its printing in 1,2 order). Can you tell me how to do this?

I know I can always write a shell script to do this reversing, but I am looking for something using the 'cut' command options.

I think I am using version 5.2.1 of coreutils containing cut.

3 Answers 3

44

This can't be done using cut. According to the man page:

Selected input is written in the same order that it is read, and is written exactly once.

Patching cut has been proposed many times, but even complete patches have been rejected.

Instead, you can do it using awk, like this:

awk '{print($2,"\t",$1)}' abcd.txt

Replace the \t with whatever you're using as field separator.

1
  • Folks may be coming here confused because this (mis)behavior isn't documented in the cut man page found on *BSD/macOS. The man page references the POSIX.2 standard which does indeed specify the output order.
    – user11638666
    Sep 24, 2019 at 21:27
22

Lars' answer was great but I found an even better one. The issue with his is it matches \t\t as no columns. To fix this use the following:

awk -v OFS="  " -F"\t" '{print $2, $1}' abcd.txt

Where:

-F"\t" is what to cut on exactly (tabs).

-v OFS=" " is what to seperate with (two spaces)

Example:

echo 'A\tB\t\tD' | awk -v OFS="    " -F"\t" '{print $2, $4, $1, $3}'

This outputs:

B    D    A    
1
  • 3
    In Cygwin I had to replace -F"\t" with -F \t to make this work. Jul 18, 2013 at 11:39
0

Here is the perl version, just for my reference:

cat abcd.txt | perl -ne 'chomp; @F=split; print("$F[1]\t$F[0]\n")' 

I use the split explicitly because I often only want to split on \t (split("\t")).

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.