Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

How could I change the order of fields from a given command?

As an example take the output of ls -l. By default the file name is displayed as the last field of the output. What could I pipe that output to in order to make the file name the first field shown?

My initial thought was to use the cut command, but regardless of the order in which fields are passed to the -f option they're always outputted in the original order.

Note: I'm only using ls -l as an easy example, but I'd like to find a general purpose idiom that could be used for any command that outputs data in columns. If it could also be applied to delimited data that would be great too.

share|improve this question

1 Answer 1

up vote 2 down vote accepted

For a fixed number of fields you can use awk, for example to exchage second and fourth field:

command | awk '{ t = $2; $2 = $4; $4 = t; print }' | column -t

But unfortunately ls -l does not have a fixed number of field (separated by spaces) because also filenames can contain spaces: this is the reason why parsing ls -l output is discouraged.

share|improve this answer
    
I guess I shouldn't have used ls -l as my example. Thanks for the answer. –  Mike Deck Sep 9 '11 at 19:49

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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