[英]Piping find output to xargs to run python script
我在這里看到了最奇怪的結果,並希望有人可以向我解釋這一點。
因此,我使用 find 命令來定位所有 type.log 文件,並將該命令的結果傳送到 python 腳本。 只有 find 命令的第一個結果被傳送到 xargs,或者 xargs 接收所有結果並將它們作為字符串傳遞給 python 腳本。
例子:
# Find returns 3 .log files
find . -name "*.log"
file1.log
file2.log
file3.log
# xargs only runs the python script for first found file (or all 3 are being piped to script as a single string, and only first result is read in)
find . -name "*.log" | xargs python myscript.py -infile
Success: parsed file1.log
我想要發生的是 python 腳本為找到的所有 3 個文件運行。
find . -name "*.log" | xargs python myscript.py -infile
Success: parsed file1.log
Success: parsed file1.log
Success: parsed file1.log
更安全的方法如下:
find . -name "*.log" -print0 | \
xargs -0 -I {} python myscript.py -infile {}
從find
傳遞文件名時,使用 -0 或 -d 選項將分隔符設置為 \0(null)非常重要。 文件名不能包含 / 或 \0 字符,因此可以保證文件名的安全使用。
使用xargs
,您必須提供 -0 以告知使用 \0 分隔符。 您還需要:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.