[英]Xargs append string to files
我在一個目錄中有多個文本文件。 最后我想要 append 一個字符串。
例如。 目錄中的文本文件列表。
命令獲取他們的路徑:
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
及以后,因此在擴展"$@"
時被迭代)。
tee -a
! Un*x 命令tee
是為這種操作而構建的,而且速度要快得多!!
find . -type f -name '*.txt' -exec tee -a <<<'Foo bar baz' {} >/dev/null +
但是只有當tee
只執行一次時, herestring才會起作用! (感謝Charles Duffy 的評論)!
使用globstar
進一步查看純bash 。
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
的角度來看,您的命令分為三個部分:
find -name "*txt"
)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.