繁体   English   中英

如何在Bash中添加多个定界符

[英]How to add more than one delimiter in Bash

我试图弄清楚如何设置两个定界符:一个是换行符,另一个是空格,所以当我从这样填充的文件中读取数字时

1 2 3
4
5 
6

我按顺序得到一个数字1,2,3,4,5,6 我正在使用读取命令来读取数字。 谢谢!

您的问题尚不清楚,但是基于示例和预期的输出,简单的解决方案是使用tr

$ cat file | tr '[ \n]' ,
1,2,3,4,5,,6,

但是5后面有一个空格,因此您需要使用-s压缩重复序列

$ cat file | tr -s '[ \n]' ,
1,2,3,4,5,6,

仍然留下令人讨厌的结尾逗号和结尾缺少换行符。 可以用sedawk处理。 (使用蓝宝石和钢铁解说员的声音) Awk已分配

$ cat file | tr -s '[ \n]' , | awk 'sub(/,$/,"")' # fails if output is just 0
1,2,3,4,5,6                                       # add ||1 or ||$0!="" to fix

等待。 自从我们开始awk以来,为什么根本不tr

$ awk '{
    gsub(/ +/,",",p)            # replace space runs with a single comma
    printf "%s",p
    p=(p~/,$/||NR==1?"":",") $0 # 5 followed by space leaves a comma in the end so...
}
END {
    print p
}' file
1,2,3,4,5,6

好吧,结果看起来很复杂,我刚才注意到您确实提到了使用read命令,所以也许我的解决方案还不够,我应该从一开始就使用bash脚本:

s=""                     # using this neat trick I just learned here ;D
while read line          # read a full line
do 
    for word in $line    # read word by word
    do 
        echo -n $s$word  # output separator and the word
        s=,              # now set the separator 
    done
done < file
echo                     # newline to follow
1,2,3,4,5,6

是的,这是星期六晚上,我没有生命。

暂无
暂无

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

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