简体   繁体   English

Awk:在一行中删除最后一个记录分隔符

[英]Awk: Drop last record separator in one-liner

I have a simple command (part of a bash script) that I'm piping through awk but can't seem to suppress the final record separator without then piping to sed. (Yes, I have many choices and mine is sed.) Is there a simpler way without needing the last pipe?我有一个简单的命令(bash 脚本的一部分),我正在通过 awk 进行管道传输,但似乎无法在没有管道传输到 sed 的情况下抑制最终记录分隔符。(是的,我有很多选择,我的是 sed。)是有不需要最后一个 pipe 的更简单的方法吗?

dolls = $(egrep -o 'alpha|echo|november|sierra|victor|whiskey' /etc/passwd \
| uniq | awk '{IRS="\n"; ORS=","; print}'| sed s/,$//);

Without the sed, this produces output like echo,sierra,victor, and I'm just trying to drop the last comma.如果没有 sed,这会产生 output,就像echo,sierra,victor,我只是想去掉最后一个逗号。

You don't need awk, try: 您不需要awk,请尝试:

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

Here is another example: 这是另一个示例:

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

Also I think your chained command could be simplified. 另外,我认为可以简化链接命令。 awk could do all things in an one-liner. awk可以一站式完成所有工作。

除了egrep,uniq,awk,sed等之外,所有这些都可以在一个awk命令中完成:

awk -F":" '!($1 in a){l=l $1 ","; a[$1]} END{sub(/,$/, "", l); print l}' /etc/password

Here is a small and quite straightforward one-liner in awk that suppresses the final record separator: 这是awk中一个很小而很简单的单行代码,它抑制了最终的记录分隔符:

echo -e "alpha\necho\nnovember" | awk 'y {print s} {s=$0;y=1} END {ORS=""; print s}' ORS=","

Gives: 给出:

alpha,echo,november

So, your example becomes: 因此,您的示例变为:

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=",");

The benefit of using awk over paste or tr is that this also works with a multi-character ORS. 使用awk而不是paste或tr的好处是,它也可用于多字符ORS。

Since you tagged it bash here is one way of doing it: 由于您已将其标记为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"
echo "a
b
c" |
 mawk 'NF-= _==$NF' FS='\n' OFS=, RS=
a,b,c

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM