优化sed多个表达式,包括空格和方括号

时间:2014-02-12 15:05:52

标签: sed

我有以下命令正常工作,但仅仅是出于学习目的,我想知道如何将以下三个sed表达式合并为一个:

bash
[user@localhost]$ echo '[lib:Library10] [idx:10] [Fragment] [75] [color]'| sed -e 's/\]//g'  -e 's/\[//g' -e 's/\s\+/\t/g' -e 's/\:/\t/'

lib     Library10       idx:10  Fragment        75      color

2 个答案:

答案 0 :(得分:3)

sed 's/[][]//g; s/:\|\s\+/\t/g'

示范:

$ echo '[lib:Library10] [idx:10] [Fragment] [75] [color]'| sed 's/[][]//g; s/:\|\s\+/\t/g'
lib Library10   idx 10  Fragment    75  color
$ echo '[lib:Library10] [idx:10] [Fragment] [75] [color]'| sed 's/[][]//g; s/:\|\s\+/\t/g' | od -c
0000000   l   i   b  \t   L   i   b   r   a   r   y   1   0  \t   i   d
0000020   x  \t   1   0  \t   F   r   a   g   m   e   n   t  \t   7   5
0000040  \t   c   o   l   o   r  \n
0000047

如果要在字符类中放置右括号,它必须是第一个字符,因此[][]将匹配左括号或右括号。

答案 1 :(得分:2)

您可以将其分为两个区块:

$ sed -re 's/(\]|\[)//g' -e 's/(\s+|\:)/\t/g' <<< "[lib:Library10] [idx:10] [Fragment] [75] [color]"
lib     Library10       idx     10      Fragment        75      color

即,

sed -e 's/\]//g'  -e 's/\[//g'   -e 's/\s\+/\t/g' -e 's/\:/\t/'
    --------------------------   ------------------------------
    |     delete ] and [     |   | replace \s+ and : with tab |
    --------------------------   ------------------------------
      -re 's/(\]|\[)//g'              -e 's/(\s+|\:)/\t/g'

分段:

sed -e 's/\]//g'  -e 's/\[//g'

可以压缩为:

sed -re 's/(\]|\[)//g'

将条件与(condition1|condition2)语句和-r sed一起加入。

与其他表达方式相同。


作为旁注,tr可以更好地删除[]字符:

$ echo '[lib:Library10] [idx:10] [Fragment] [75] [color]' | tr -d '[]' 
lib:Library10 idx:10 Fragment 75 color

要将:替换为\t,您还可以使用tr

$ echo '[lib:Library10] [idx:10] [Fragment] [75] [color]' | tr ':' '\t'
[lib    Library10] [idx 10] [Fragment] [75] [color]
相关问题