将 find 输出传递给 xargs 然后传递给 sed 时的随机行为
Random behaviour when pipping find output to xargs and then to sed
我使用的是这些工具的 gnu 版本。我正在尝试解压缩存档并转换文件。
文件是“myfile.txt”,它出现在存档的多个文件夹中 - 所以我认为将完整路径传递给 xarg 会转换所有文件:
mkdir temp
unzip mypackage.zip -d temp
find temp -iname "myfile.txt" | xargs -I FILE sh -c "sed -e 's/replacethis/withthis/g' -e 's/replacethistoo/withthisaswell/g' FILE | tee FILE"
# List the files
find temp -iname "myfile.txt" | xargs -I FILE ls -l FILE
# Cat the files
find temp -iname "myfile.txt" | xargs -I FILE cat FILE
# Clean up
rm -Rf temp
我 运行 这个脚本多次,结果不同,我不明白。
每次修改不同的“myfile.txt”,有时其中一个“myfile.txt”文件有0字节
为什么会这样?每次都应该一样,不是吗?每次我 运行 这个脚本时,find 是否只传递一个随机的“myfile.txt”到 xargs 的路径?
Why is this happening? It should be the same every time shouldnt it?
发生这种情况是因为以下两个并行操作之间存在竞争条件:
sed
打开并读取文件
tee
打开和截断文件
如果tee
获胜,当sed
读取文件时文件将为空,因此为0字节。
如果 sed
获胜,它将读取(至少部分)文件,您将获得一些数据。
由于进程调度是不可预测的,因此您可能每次都会看到不同的结果。
我使用的是这些工具的 gnu 版本。我正在尝试解压缩存档并转换文件。
文件是“myfile.txt”,它出现在存档的多个文件夹中 - 所以我认为将完整路径传递给 xarg 会转换所有文件:
mkdir temp
unzip mypackage.zip -d temp
find temp -iname "myfile.txt" | xargs -I FILE sh -c "sed -e 's/replacethis/withthis/g' -e 's/replacethistoo/withthisaswell/g' FILE | tee FILE"
# List the files
find temp -iname "myfile.txt" | xargs -I FILE ls -l FILE
# Cat the files
find temp -iname "myfile.txt" | xargs -I FILE cat FILE
# Clean up
rm -Rf temp
我 运行 这个脚本多次,结果不同,我不明白。
每次修改不同的“myfile.txt”,有时其中一个“myfile.txt”文件有0字节
为什么会这样?每次都应该一样,不是吗?每次我 运行 这个脚本时,find 是否只传递一个随机的“myfile.txt”到 xargs 的路径?
Why is this happening? It should be the same every time shouldnt it?
发生这种情况是因为以下两个并行操作之间存在竞争条件:
sed
打开并读取文件tee
打开和截断文件
如果tee
获胜,当sed
读取文件时文件将为空,因此为0字节。
如果 sed
获胜,它将读取(至少部分)文件,您将获得一些数据。
由于进程调度是不可预测的,因此您可能每次都会看到不同的结果。