我有一个简单的命令(bash脚本的一部分),我正在通过awk进行管道但是似乎无法抑制最终的记录分隔符,而没有管道到sed。 (是的,我有很多选择,我的是sed。)是否有更简单的方法而不需要最后一根管道?
dolls = $(egrep -o 'alpha|echo|november|sierra|victor|whiskey' /etc/passwd \
| uniq | awk '{IRS="\n"; ORS=","; print}'| sed s/,$//);
没有sed,这会产生类似echo,sierra,victor,
的输出,而我只是想删掉最后一个逗号。
答案 0 :(得分:4)
你不需要awk,试试:
egrep -o ....uniq|paste -d, -s
这是另一个例子:
kent$ echo "a
b
c"|paste -d, -s
a,b,c
此外,我认为您的链式命令可以简化。 awk可以用单行做所有事情。
答案 1 :(得分:2)
而不是egrep,uniq,awk,sed等,所有这一切都可以在一个awk命令中完成:
awk -F":" '!($1 in a){l=l $1 ","; a[$1]} END{sub(/,$/, "", l); print l}' /etc/password
答案 2 :(得分:1)
这是awk中一个小而且非常简单的单行代码,用于抑制最终记录分隔符:
echo -e "alpha\necho\nnovember" | awk 'y {print s} {s=$0;y=1} END {ORS=""; print s}' ORS=","
给出:
alpha,echo,november
所以,你的例子变成了:
dolls = $(egrep -o 'alpha|echo|november|sierra|victor|whiskey' /etc/passwd | uniq | awk 'y {print s} {s=$0;y=1} END {ORS=""; print s}' ORS=",");
使用awk而不是paste或tr的好处是,这也适用于多字符ORS。
答案 3 :(得分:0)
由于您标记了bash
,因此这是一种方法:
#!/bin/bash
# Read the /etc/passwd file in to an array called names
while IFS=':' read -r name _; do
names+=("$name");
done < /etc/passwd
# Assign the content of the array to a variable
dolls=$( IFS=, ; echo "${names[*]}")
# Display the value of the variable
echo "$dolls"