Albert
Albert

Reputation: 142

Adding a column with awk

I want to add a new column at the beggining of every row. Command used:

tree -afispugD --inodes

I want to put a new column which will be the name of the file.

Example:

119801433 -rwxr--r-- u1915811 alum          1252 Apr  1 21:06  ./file
119802284 -rw-r--r-- u1915811 alum          1255 Mar 20 10:25  ./text.txt
119865862 drwxr-xr-x u1915811 alum          4096 Feb 27 10:20  ./S3/folder2

To this:

file       119801433 -rwxr--r-- u1915811 alum          1252 Apr  1 21:06  ./file
text.txt   119802284 -rw-r--r-- u1915811 alum          1255 Mar 20 10:25  ./text.txt
folder2    119865862 drwxr-xr-x u1915811 alum          4096 Feb 27 10:20  ./S3/folder2

PS: I have to do it because tree command doesn't show names :(

Upvotes: 0

Views: 275

Answers (3)

Zsolt Botykai
Zsolt Botykai

Reputation: 51693

Until there are spaces in the filenames, this should work:

tree -afispugD --inodes | awk '{printf("-30s%s\n",$NF,$0}'

Upvotes: 0

A human being
A human being

Reputation: 1220

This one will also work, if file has whitespaces in its name or if it's a symbolic link

tree -afispugD --inodes | awk '{FS="./"; ORS=""; printf("%-60s%s\n",$NF,$0)}'

Upvotes: 0

Ed Morton
Ed Morton

Reputation: 204731

All you need is:

$ awk -F'/' '{print $NF,$0}' file
file 119801433 -rwxr--r-- u1915811 alum          1252 Apr  1 21:06  ./file
text.txt 119802284 -rw-r--r-- u1915811 alum          1255 Mar 20 10:25  ./text.txt
folder2 119865862 drwxr-xr-x u1915811 alum          4096 Feb 27 10:20  ./S3/folder2

or if you want to use some specific spacing in the output use printf instead of print:

$ awk -F'/' '{printf "%-10s%s\n",$NF,$0}' file
file      119801433 -rwxr--r-- u1915811 alum          1252 Apr  1 21:06  ./file
text.txt  119802284 -rw-r--r-- u1915811 alum          1255 Mar 20 10:25  ./text.txt
folder2   119865862 drwxr-xr-x u1915811 alum          4096 Feb 27 10:20  ./S3/folder2

or, since this is a simple substitution on a single line, you could use sed instead of awk:

$ sed 's/\(.*\/\(.*\)\)/\2 \1/' file
file 119801433 -rwxr--r-- u1915811 alum          1252 Apr  1 21:06  ./file
text.txt 119802284 -rw-r--r-- u1915811 alum          1255 Mar 20 10:25  ./text.txt
folder2 119865862 drwxr-xr-x u1915811 alum          4096 Feb 27 10:20  ./S3/folder2

Upvotes: 1

Related Questions