xargs 没有正确地逐行读取

xargs does not read line by line properly

这是我当前使用的命令:

xargs -n 1 -P 100 php b <links

我有一个脚本 'b' 和一个在 'links' 中带有链接的文件,有时我不知道为什么这不能正常工作并添加到每一行符号“?” 像这样:

root     19714  0.0  1.0  19880  5480 pts/2    R+   11:19   0:00 php b http://www.google.com?
root     19715  0.0  0.9  19524  4892 pts/2    R+   11:19   0:00 php b http://www.alexa.com?
root     19716  0.0  1.0  19880  5496 pts/2    R+   11:19   0:00 php b http://www.amazon.com?

看到 ps-aux 结果行的末尾是“?”符号,我的文件不包含那个...但不是所有时候...可能是什么问题?

将评论转化为答案

您的链接文件可以有 CRLF(Windows 或 DOS 风格)行尾吗?在这种情况下,? 代表 CR(回车符 return)……修复方法是将 DOS 文件转换成 Unix 文件。例如:

tr -d '\r' < links | xargs -n 1 -P 100 php b

I build the links file with cat "[another file]" | sort | uniq > links. So I don't think it is a Windows/DOS style issue.

[another file] 是否有 DOS 格式的行结尾?如果是这样,links 也会;如果它们在输入中,命令行将保留 CRLF 行结尾。

此外,通常不需要使用 catUUoC 或无用的 Cat),在这种情况下也不需要 uniq;你可以使用

sort -u "[another file]" > links

[another file] is like this:

line1\r\nline2\r\nline3\r\n

\r\n 是在 Unix 上报告 CRLF 行结尾的方式之一。 \r表示法在C等语言中用于回车return、CR; \n 符号用于换行符(NL,又名换行符或 LF)。

BTW: If I paste the same file with copy/paste via vi or nano it works.

编辑器可能会自动为您转换文件格式。请参阅:How to convert the ^M linebreak to normal linebreak in a file opened in vim? 或者,如果您正在复制和粘贴,则副本可能看不到,因此不会复制 CR 字符。

I tried with tr -d … and it works.

很好;这至少意味着这是一个合理的解释,而且一切都说得通。如果你不需要单独的链接列表,你可以使用:

sort -u "[another file]" | tr -d '\r' | xargs -n 1 -P 100 php b

这一切都在一个命令行中完成,无需清理中间文件。当然,如果您也想要文件列表,可以在 xargs 之前添加 tee links |