【问题标题】:Remove new line from find command output从 find 命令输出中删除新行
【发布时间】:2014-07-25 11:01:23
【问题描述】:

我想在一个命令中将 find 命令的输出与我的一个脚本一起使用。

我的脚本接受:

some-script --input file1.txt file2.txt file3.txt --output final.txt

我想用 `find 命令替换 file1.txt file2.txt file3.txt

some-script --input `find ./txts/*/*.txt` --output final.txt

但这会中断,因为 find 命令的输出中有新行。

【问题讨论】:

  • 尝试使用 -print0 参数查找,这将在没有换行符的情况下打印结果

标签: shell terminal


【解决方案1】:

Find 可以在不依赖其他命令的情况下输出以空格分隔的结果列表:

find . -name someFile -type f -printf "%p "

上面会在当前目录或任意子目录中查找所有名为“someFile”的文件,然后不换行打印结果。

例如,给定这个目录树:

.../dir1/someFile.txt
.../dir1/dir2/someFile.txt

从 dir1 运行 find . -name '*.txt' -type f -printf "%p " 将输出:

someFile.txt ./dir2/someFile.txt

传递给上述find 命令的参数、选项和“动作”(即-printf)可以修改如下:

  • 如果您不提供-type f 选项,find 将报告名为someFile 的所有类型的文件系统条目。此外,find 的手册页列出了可以提供给 -type 的其他参数,这些参数将导致 find 仅搜索目录、仅搜索可执行文件或仅搜索链接等...
  • -printf "%p " 更改为 -printf "%f " 以打印无路径的文件名,或者再次参见 find 的手册页了解 findprintf 操作接受的其他格式规范。
  • . 更改为其他目录路径以搜索其他目录树。

【讨论】:

    【解决方案2】:

    这应该适用于您使用的任何 shell 脚本语言..

    例子:

    find . -type f | grep "\.cc" > ~/lolz.tmp
    tr '\n' ' ' < ~/lolz.tmp
    

    你的例子:

    find ./txts/*/*.txt > ~/lolz2.tmp
    tr '\n' ' ' < ~/lolz2.tmp
    

    【讨论】:

    • 当你可以使用管道时,为什么还要使用额外的临时文件??
    • 当然你也可以使用管道,所有这些工具都支持
    • tr -d '\n' 怎么样?
    【解决方案3】:

    为什么不使用 ls 命令而不是 find 命令。 例如 一些脚本 --input ls ./txts/*/*.txt --output final.txt ls 将文件输出为 ./txt/file1.txt ./txt/one/file2.txt .. etc

    编辑—— 您可以使用 find 并将换行符替换为空格,如下所示:
    some-script --input find ./txts/*/*.txt | tr '\n' ' ' --output final.txt

    【讨论】:

    • 不知道 ls 是否会在其他地方支持,也不给一个空格
    猜你喜欢
    • 2017-11-15
    • 2021-01-04
    • 2017-01-31
    • 2023-04-09
    • 2012-10-28
    • 1970-01-01
    • 2011-01-28
    • 2015-06-17
    • 1970-01-01
    相关资源
    最近更新 更多