繁体   English   中英

Xargs append 字符串到文件

[英]Xargs append string to files

我在一个目录中有多个文本文件。 最后我想要 append 一个字符串。

例如。 目录中的文本文件列表。

  • 一个.txt
  • b.txt
  • c.txt

命令获取他们的路径:

find -name "*txt"

然后我试着发送

'echo "example text" > <filename>

所以我尝试运行以下命令:

find -name "*txt" | xargs echo "example_text" >>

此命令失败。

我想要的只是 append 时不时地向文件添加一些文本,因为文件的名称不断变化,我想使用 xargs

xargs在这里并不合适。 也许循环遍历文件名

for file in *.txt; do
    echo "example_text" >>"$file"
done

因为>>是一个 shell 指令,如果你想通过 xargs 兑现它,你需要让 xargs 启动一个 shell。正如Shawn 的回答所示,在许多情况下,一个 shell glob 就足够了,你根本不需要find ; 但是如果你确实想使用find ,无论有没有 xargs 都可以正确使用它。


如果您坚持使用xargs ,即使它不是完成这项工作的最佳工具......

find . -name "*.txt" -print0 | xargs -0 sh -c '
  for arg in "$@"; do echo "example_text" >>"$arg"; done
' _

取出xargs ,仅使用find (使用-exec... {} +获得xargs否则会提供的相同性能优势):

find . -name "*.txt" -exec sh -c '
  for arg in "$@"; do echo "example_text" >>"$arg"; done
' _ {} +

(在上面两个中, _替代$0 ,所以后来 arguments 变成$1及以后,因此在扩展"$@"时被迭代)。

Append 一个字符串到多个文件,使用tee -a !

Un*x 命令tee是为这种操作而构建的,而且速度要快得多!!

find . -type f -name '*.txt' -exec tee -a <<<'Foo bar baz' {} >/dev/null +

但是只有当tee只执行一次时, herestring才会起作用! (感谢Charles Duffy 的评论)!

使用globstar进一步查看

如果你真的想使用xargs

find . -type f -name '*.txt' -print0 |
    xargs -0 sh -c 'echo "Foo bar baz"|tee -a "$@" >/dev/null ' _

但是find真的需要吗?

如果所有文件都在同一目录下:

tee -a <<<'Foo bar baz' >/dev/null *.txt

否则,在 [ŧag:bash] 下,使用globstar ( shopt -s globstar ):

tee -a <<<'Foo bar baz' >/dev/null **/*.txt

正如许多人指出的那样, xargs不合适,因此您可以简单地使用 find 和 pipe 循环read以轻松完成您想要的操作,如下所示。

find . -name "*.txt" | while read fname; do echo "example_text">>$fname; done

bash的角度来看,您的命令分为三个部分:

  • 在 pipe 字符之前( find -name "*txt"
  • 在 pipe 和重定向之间( xargs echo "example_text"
  • 重定向后( )

bash尝试打开重定向后提供的 output 文件,但是由于您没有提供任何内容, bash无法打开“无”并失败。

要解决您的问题,您需要为xargs提供一种将所需行添加到文件的方法(无需要求bash重定向xargs的 output)。 一种可行的方法是启动一个执行该操作的子 shell:

find -name "*txt" | xargs -I{} bash -c 'echo "example_text" >> {}'

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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