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.


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.

| 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

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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