2013-03-12 54 views
1

我了解xargs工具,它可以让我行转换成多个参数,比如:在如何从文件行组成自定义命令行参数?

echo -e "a\nb\nc\n" | xargs 

结果:

a b c 

但我想:

a:b:c 

以字符:为例。我希望能够在行之间插入任何分隔符以获得单个参数。我该怎么做?

回答

1

如果你有多个行的文件比你想改变一个参数由单个字符改变换行符的paste命令是你需要的东西:

$ echo -en "a\nb\nc\n" | paste -s -d ":" 
a:b:c 

然后,你的命令变为:

your_command "$(paste -s -d ":" your_file)" 

编辑:

如果要插入多单字符作为分隔符时,您可使用sedpaste

your_command "$(sed -e '2,$s/^/<you_separator>/' your_file | paste -s -d "")" 

或者使用一个更复杂的sed

your_command "$(sed -n -e '1h;2,$H;${x;s/\n/<you_separator>/gp}' your_file)" 
1

你给的例子不适合我。您需要:

echo -e "a\nb\nc\n" | xargs 

得到a b c

再回到你的需要,你可以这样做:

echo "a b c" | awk 'OFS=":" {print $1, $2, $3}' 

它将从空间分隔变为:或任何你希望它是。

您还可以使用sed

echo "a b c" | sed -e 's/ /:/g 

将输出a:b:c

经过所有这些数据处理后,您可以使用xargs来执行您想要的命令。只需| xargs并做任何你想做的事情。

希望它有帮助。

+0

你是对的约例如 - 我会更新我的问题。 – 2013-03-12 09:53:06

0

您可以使用xargs加入行,然后使用sed替换空格(' ')。

echo -e "a\nb\nc"|xargs| sed -e 's/ /:/g'

将导致

a:b:c

明显可以使用其他xargs使用此输出参数为其它命令。

echo -e "a\nb\nc"|xargs| sed -e 's/ /:/g'|xargs