【发布时间】:2020-01-05 02:39:08
【问题描述】:
在以下 bash 脚本中,我将文件列表从路径捕获到变量中,然后将其传递到 xargs 以进行进一步操作。
我发现只需 echoing 变量即可为每一行适当地添加空格,并为每一行添加一个换行符终止符。但是,当我将printf 或echo 转到xargs 时,我发现xargs 似乎也将每一行的输入都用空格分隔。我将用下面的例子用 cmets 来说明,包括我看到的结果:
# Using GNU find:
list="$( find '$SOME_PATH' -type f )"
excluded_list="$( egrep -v -f FILE_WITH_PATTERNS_OF_FOLDERS_TO_EXCLUDE <<< $list )"
# This prints out just fine with lines such as "/some/path/here with spaces" on their own line, eg:
# /some/path/here with spaces
# /another/path/here with spaces
# /and yet another/path/here with spaces
echo "$excluded_list"
# But this prints out a line such as the above example "/some/path/here with spaces" broken up like this instead:
# /some/path/here
# with
# spaces
# /another/path/here
# with
# spaces
# /and
# yet
# another/path/here
# with
# spaces
printf "%s" "$excluded_list" | xargs -n 1 -P 1 sh -c 'echo "$0"'
# And the same result as `printf` above:
echo "$excluded_list" | xargs -n 1 -P 1 sh -c 'echo "$0"'
【问题讨论】:
-
如果您希望
xargs采用整行而不是在[:blank:]字符类上拆分,则使用xargs -L 1。我邀请您阅读 xargs 的手册页以了解-l[max-lines], --max-lines[=max-lines]选项的说明。 -
"
xargs从标准输入读取项目,由空格(可以用双引号或单引号或反斜杠保护)或换行符分隔"