Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Forcing the order of output fields from cut command

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.

like image 237
Shreeni Avatar asked Jun 24 '09 08:06

Shreeni


People also ask

What happens when you use the cut command?

The cut command is a command-line utility that allows you to cut out sections of a specified file or piped data and print the result to standard output. The command cuts parts of a line by field, delimiter, byte position, and character.

Which option is used with the cut command for cutting fields?

The cut command uses tab as the default delimiter to cut fields.

How cut command is used in Linux with example?

The cut command in UNIX is a command for cutting out the sections from each line of files and writing the result to standard output. It can be used to cut parts of a line by byte position, character and field. Basically the cut command slices a line and extracts the text.


2 Answers

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.

like image 92
Lars Haugseth Avatar answered Oct 12 '22 23:10

Lars Haugseth


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     
like image 32
Evan Moran Avatar answered Oct 13 '22 00:10

Evan Moran