【问题标题】:Remove multiple spaces in ls -l output删除 ls -l 输出中的多个空格
【发布时间】:2016-09-19 05:05:09
【问题描述】:

我需要显示文件大小和文件名。像这样:

4.0K Desktop

我正在使用 ls -l 输出中的 cut 提取这两个字段:

ls -lhS | cut -d' ' -f5,9

由于ls -l 输出中有多个空格,我得到了一些错误的输出,例如:

4.0K 19:54
4.0K 19:55
 6
 18:39
 31
 25

我应该如何解决这个问题?

我只需要使用管道而不需要 bash 脚本(输出可以是多个管道)来完成这项任务,最好不要使用 sed、awk。

如果没有 sed 或 awk 的替代品可用 - 可以使用 sed。

【问题讨论】:

  • 为什么不使用du -sh *
  • 你试过给tr -s ' '然后解析吗?
  • @spasic :你应该把它作为答案。
  • @PS。问题的细节似乎是一个练习问题.. 等待 OP 澄清
  • @spasic : 用于演示类

标签: linux bash shell command-line


【解决方案1】:

can avoid parsing ls output 并使用 stat 命令作为 bash 中 GNU coreutils 的一部分来获取详细的文件信息。

 # -c  --format=FORMAT
 #         use the specified FORMAT instead of the default; output a newline after each use of FORMAT

 # %n     File name
 # %s     Total size, in bytes

 stat -c '%s %n' *

【讨论】:

  • 嘿,我收到了这个stat: cannot stat %n':没有这样的文件或目录 stat: cannot stat *': No such file or directory
  • @PS。使用stat -c '%s %n' *
【解决方案2】:

你可以在使用剪切之前使用翻译字符命令。

ls -lhS | tr -s ' ' | cut -d' ' -f 5,9

【讨论】:

    【解决方案3】:

    或者你可以直接提交给 awk:

    $ ls -lhS | awk '$0=$5 OFS $9'
    

    即。将整条记录 $0 替换为字段 $5$9,由输出字段分隔符 OFS 分隔。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-20
      相关资源
      最近更新 更多