104

While playing with awk I came to execute:

ls -la >> a.txt ; awk {'print $5  $1'} a.txt ;

This is giving output like:

53277-rw-------
52347-rw-------

How can I get a space between these two friends of output?

muru
  • 197,895
  • 55
  • 485
  • 740
Raja G
  • 102,391
  • 106
  • 255
  • 328

5 Answers5

130

Just change the line to

ls -la >> a.txt ; awk {'print $5 "        " $1'} a.txt ;

this should print the output with spaces.

Hope this helps.

Edit:

As suggested by McNisse you can use printf, which would provide you good output format

ls -la >> a.txt ; awk {'printf ("%5s\t%s\n", $5, $1)'} a.txt ;
devav2
  • 36,312
  • 8
    The printf function provides better control, specially if you want to format numbers. printf("%s\t%s\n", $5, $1) – McNisse Dec 23 '12 at 10:11
  • 1
    Is there a typo in above answer? what does 5s mean in awk {'printf ("%5s\t%s\n", $5, $1)'} – Vishal Oct 15 '19 at 13:06
  • @Vishal - if you insert a number after the % sign, then you specify a field width, in this case 5. The output will be right aligned. If you enter a negative number, the output will be aligned on the left. – twan163 Nov 22 '19 at 15:55
101

Another awk-specific technique, use the "output field separator"

ls -la | awk -v OFS='\t' '{print $5, $1}'

The comma is crucial here.

glenn jackman
  • 17,900
26

A simple way to get tabs is:

awk {'print $5"\t"$1'}
a06e
  • 13,223
  • 26
  • 70
  • 104
9

I know this is an old thread, but I'm just learning and found these posts helpful. My best solution was to use gawk to insert spaces between the variables for you.

ls -la | gawk '{print $1, $9}'
6

To place the space between the arguments, just add " ", e.g. awk {'print $5" "$1'}.

However it is not recommended to parse output of ls command, since it's not reliable and output is for humans, not scripts. Therefore use alternative commands such as find or stat.

Here is example using GNU stat:

$ stat -t *
001.txt 23 8 81a4 501 20 1000004 242236402 1 0 0 1460260387 1460260239 1460260239 1460260194 4096
7c1c.txt 21 8 81a4 501 20 1000004 242236595 1 0 0 1460261322 1460260486 1460260486 1460260486 4096

which will print you machine-friendly output (in terse form), so you can get exactly what you need. Then use -c to use specific format, or use awk, cut or read to get the right columns.

Check stat --help for further options. For example to print day of modification, check this example.

kenorb
  • 10,347
  • It appears the OP is trying to parse the output for human reading purposes and not for the purposes of running a script (like for i in ls; do $i). – mchid Nov 05 '19 at 18:15