Can I change the order of the output fields in the Linux cut command?

I use the cut command on the command line and it seems I canโ€™t get the result that I like. Do you have any idea why I am getting this? Is this something I'm doing wrong?

This is normal output, and I would like to output it in a different order:

[ root@upbvm500 root]# ls -al IDS_DIR/a | tr -s " " -rw-r--r-- 1 root root 0 Jan 1 17:18 IDS_DIR/a [ root@upbvm500 root]# [ root@upbvm500 root]# ls -al IDS_DIR/a | tr -s " " | cut -d" " -f5,6,7,8,3,4,1 -rw-r--r-- root root 0 Jan 1 17:18 

But, as you can see, this does not work as expected. Any idea why they are switching places?

+7
source share
3 answers

From man cut :

The selected input is recorded in the same order in which it is read, and recorded exactly once.

Use awk '{print $5,$6,$7,$8,$3,$4,$1}' instead of cut .

+20
source

cut does not change the order of output. It simply compiles a list of columns to print, then prints them as they become available.

Use another tool such as Awk to reorder the output columns.

However, in this case, try stat or find instead of ls . It is generally not recommended to parse the output from ls . See http://mywiki.wooledge.org/ParsingLs

+6
source

As already mentioned, do not disassemble ls. If you want to get file information, use stat

 stat -c "%s %y %U %G %A %n" filename 

You may need to do extra work to format the timestamp as you want.

 $ ls -l data -rw-r--r-- 1 glennj glennj 13 2013-01-01 11:19 data $ LC_TIME=POSIX ls -l data -rw-r--r-- 1 glennj glennj 13 Jan 1 11:19 data $ stat -c "%s %y %U %G %A %n" data 13 2013-01-01 11:19:53.670015242 -0500 glennj glennj -rw-r--r-- data $ stat -c "%s %Y %U %G %A %n" data | awk '{$2 = strftime("%b %e %H:%M", $2)} 1' 13 Jan 1 11:19 glennj glennj -rw-r--r-- data 
+6
source

All Articles