简体   繁体   中英

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 :(

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

如果文件名称中包含空格或符号链接,则此文件也可以使用

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

在文件名中没有空格之前,这应该起作用:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM