9

I am using cut command in command line and seems I can't get the output I like. Do you have any idea why I am getting this? Is it something that I do wrong?

This is the normal output and I would like to output in 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 is not working like expected. Any idea why they are switching places?

Todd A. Jacobs
  • 81,402
  • 15
  • 141
  • 199
Alexis Cimpu
  • 301
  • 1
  • 3
  • 11

3 Answers3

25

From man cut:

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

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

Chris Seymour
  • 83,387
  • 30
  • 160
  • 202
6

cut does not reorder its output. It simply collects a list of which columns to print, then prints them out as they arrive.

Use a different tool such as Awk to reorder output columns.

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

tripleee
  • 175,061
  • 34
  • 275
  • 318
6

As others have mentioned, don't parse ls. If you want file information, use stat

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

You may need to do some extra work to get the timestamp formatted 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
glenn jackman
  • 238,783
  • 38
  • 220
  • 352