【问题标题】:How to tell find command to escape space characters in file names?如何告诉 find 命令转义文件名中的空格字符?
【发布时间】:2017-07-17 22:31:42
【问题描述】:

我有一个单行查找命令,它递归地检查并打印出在特定时间范围内创建的特定文件类型的大小、所有者和名称。但在结果中,文件名列一直给出,直到目录或文件名中的第一个空格字符。 有什么想法可以在这个单个命令中解决这个问题而不在 bash 中编写任何循环吗?谢谢!

命令如下:

find /path/to/dist -type f -iname "*.png" -newermt 2015-01-01 ! -newermt 2016-12-31 -ls | sort -k5 | sort -k5 | awk '{print $5"\t"$7"\t"$11}'

【问题讨论】:

  • Shell 转义名称对您没有帮助。 sort 不知道转义。

标签: bash find


【解决方案1】:

find-print0 操作可能是起点。来自 find 的手册页:

   -print0
          True;  print  the  full file name on the standard output,
          followed by a null  character  (instead  of  the  newline
          character that -print uses).  This allows file names that
          contain newlines or other types of white space to be cor‐
          rectly interpreted by programs that process the find out‐
          put.  This option corresponds to the -0 option of xargs.

但是find 有更好的printf 操作:

find /path/to/dist -type f -iname "*.png" -newermt 2015-01-01 ! -newermt 2016-12-31 -printf "%u\t%s\t%p\n" | sort

可能会完成这项工作。

【讨论】:

  • -print0 的问题是他需要一个ls 选项来获取有关所有者和大小的信息。
  • 你是对的。我建议使用完成这项工作的命令将输出提供给xargs。但它可能比需要的更复杂。我编辑了我的答案以提出更好的方法。
【解决方案2】:

我找到了以下解决方案。您隐藏文件名中的空格。我用 sed 做的,我用了一个奇怪的链“!!!”取代 ”\ ”。然后我在 awk 命令中替换它。这是我用于测试的命令:

find . -type f -iname "*.pdf" -newermt 2015-01-01  -ls |sed 's/\\ /!!!/g' | sort -k5 | awk '{gsub("!!!"," ",$11);print $5"\t"$7"\t"$11}'

【讨论】:

  • 谢谢阿诺!这很好用!对于人类可读的大小,我使用 exec 对其进行了一些更改,列也应该更改: find /path/to/Dist -type f -iname "*.pdf" -newermt 2015-01-01 ! -newermt 2016-12-31 -exec ls -lh {} \; |sed 's/\\ /!!!/g' |排序-k5 | awk '{gsub("!!!"," ",$11);print $3"\t"$5"\t"$9}'
【解决方案3】:

尝试将您的 awk 命令更改为:

awk '{$1=$2=$3=$4=$6=$8=$9=$10="" ; print$11}'

这样整个命令就变成了这样:

find /path/to/dist -type f -iname "*.png" -newermt 2015-01-01 ! -newermt 2016-12-31 -ls | sort -k5 | awk '{$1=$2=$3=$4=$6=$8=$9=$10="" ; print$0}'

这会在行首留下一些额外的空格,希望它适用于您的目的。

我删除了sort 的第二个实例,因为它与第一个使用相同的键进行排序,这似乎没有任何作用。

【讨论】:

    【解决方案4】:

    感谢 Arno 的输入,下面这行代码完成了这项工作。我使用了 exec (-exec ls -lh {} \;) 来使大小可读:

    find /Path/To/Dest/ -type f -iname "*.pdf" -newermt 2015-01-01 ! -newermt 2016-12-31 -exec ls -lh {} \; |sed 's/\\ /!!!/g' | sort -k5 | awk '{gsub("!!!"," ",$11);print $3"\t"$5"\t"$9}'
    

    【讨论】:

      猜你喜欢
      • 2019-12-08
      • 2018-04-14
      • 2015-09-29
      • 2012-03-04
      • 2014-09-24
      • 2017-05-29
      • 1970-01-01
      • 2019-08-25
      • 2015-10-31
      相关资源
      最近更新 更多