簡體   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