1

我有一个简单的命令(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,,我只是想删除最后一个逗号。

4

4 回答 4

4

你不需要awk,试试:

egrep -o ....uniq|paste -d, -s

这是另一个例子:

kent$  echo "a
b
c"|paste -d, -s
a,b,c

另外我认为您的链接命令可以简化。awk 可以在一条线中完成所有事情。

于 2013-07-17T21:14:08.583 回答
2

代替 egrep、uniq、awk、sed 等,所有这些都可以在一个 awk 命令中完成:

awk -F":" '!($1 in a){l=l $1 ","; a[$1]} END{sub(/,$/, "", l); print l}' /etc/password
于 2013-07-17T21:13:55.473 回答
2

这是 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。

于 2016-08-30T13:26:53.133 回答
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"
于 2013-07-18T01:49:12.937 回答