使用awk格式化没有制表符的ls输出?

Formatting ls output without tab using awk?

我的问题可能看起来很简单,我仍然是 bash 脚本编写的初学者,但我试图在使用 awk 打印时不使用制表符来格式化我的 ls 输出。

这是我当前的命令 运行:

ls -al | sed 1d | awk '{print " "," ", "\t", }'

并打印出以下内容

drwx------  Feb  13     .
drwxr-xr-x  Feb  5      ..
-rw-r--r--  Jan  21     .alias
-rw-r--r--  Feb  13     .bash_history
-rw-r--r--  Jan  29     .bash_profile
-rw-r--r--  Jan  21     .bash_profile~
-rw-r--r--  Feb  13     .bashrc
-rw-r--r--  Jan  21     .bashrc~
drwxr-xr-x  Jan  3      csc135
drwxr-xr-x  Aug  13     csc136
drwxr-xr-x  Feb  9      csc235
drwxr-xr-x  Oct  19     csc237
drwxr-xr-x  Feb  18     csc310
drwxr-xr-x  Feb  6      csc325

我也尝试过使用 space:

ls -al | sed 1d | awk '{print "  "," ", " ", }'

打印以下内容(相当麻烦):

drwx------   Feb  13  .
drwxr-xr-x   Feb  5  ..
-rw-r--r--   Jan  21  .alias
-rw-r--r--   Feb  13  .bash_history
-rw-r--r--   Jan  29  .bash_profile
-rw-r--r--   Jan  21  .bash_profile~
-rw-r--r--   Feb  13  .bashrc
-rw-r--r--   Jan  21  .bashrc~
drwxr-xr-x   Jan  3  csc135
drwxr-xr-x   Aug  13  csc136
drwxr-xr-x   Feb  9  csc235
drwxr-xr-x   Oct  19  csc237
drwxr-xr-x   Feb  18  csc310
drwxr-xr-x   Feb  6  csc325

有没有办法让它看起来更漂亮?

drwx------  Feb  13  .
drwxr-xr-x  Feb  5   ..
-rw-r--r--  Jan  21  .alias
-rw-r--r--  Feb  13  .bash_history
-rw-r--r--  Jan  29  .bash_profile
-rw-r--r--  Jan  21  .bash_profile~
-rw-r--r--  Feb  13  .bashrc
-rw-r--r--  Jan  21  .bashrc~
drwxr-xr-x  Jan  3   csc135
drwxr-xr-x  Aug  13  csc136
drwxr-xr-x  Feb  9   csc235
drwxr-xr-x  Oct  19  csc237
drwxr-xr-x  Feb  18  csc310
drwxr-xr-x  Feb  6   csc325

想到的一个自动选项是 column:

$ ls -al | sed 1d | awk '{print ,,,}' | column -t
drwxr-xr-x+  Feb  3   .
drwxrwxrwt+  Oct  9   ..
-rw-------   Feb  12  .bash_history
-rwxr-xr-x   Oct  9   .bash_profile
-rwxr-xr-x   Feb  3   .bashrc
drwx------+  Feb  2   .cache
-rwxr-xr-x   Oct  9   .inputrc
-rwxr-xr-x   Feb  14  .mkshrc
-rwxr-xr-x   Oct  9   .profile
drwxrwx---+  Dec  13  .ssh

注意 -t 标志用于 column:

-t, --table Determine the number of columns the input contains and create a table. Columns are delimited with whitespace, by default, or with the characters supplied using the --output-separator option. Table output is useful for pretty-printing.

另一种方法是使用固定长度:

$ ls -al | sed 1d | awk '{printf "%-12s %-3s %-2s %s\n", ,,,}'
drwxr-xr-x+  Feb 3  .
drwxrwxrwt+  Oct 9  ..
-rw-------   Feb 12 .bash_history
-rwxr-xr-x   Oct 9  .bash_profile
-rwxr-xr-x   Feb 3  .bashrc
drwx------+  Feb 2  .cache
-rwxr-xr-x   Oct 9  .inputrc
-rwxr-xr-x   Feb 14 .mkshrc
-rwxr-xr-x   Oct 9  .profile
drwxrwx---+  Dec 13 .ssh

GNU Awk User's guide 中还有另一个例子。

ls -al|awk  'NR>1{print ,,,}'|column -t

您不需要使用 sed 删除第一行。如果 NR>1 print

,awk 可以做到这一点

您可以使用 awk 的功能避免所有不必要的管道。

ls -al | awk -v OFS="\t" 'NR>1 { print , , ,  }'
  • 使用NR>1去掉不需要的sed删除第一行。
  • 使用 OFS 变量将输出字段分隔符设置为制表符,不再需要 column