Shell Delete sed

问题描述

| 我有一个包含一些数据的文件,如下所示:
1,3,0
0,4,5,5
2,6,1,0
我想编写一个Shell脚本来删除第3个参数为0的所有行(此处是第1和2行) 我已经知道了
sed -i \'/0/d\' file.txt
但是我不知道如何选择第三个参数。 你有想法吗?     

解决方法

Awk可能比sed更好,可以完成此任务:
awk -F\' *,*\' \'$3 != 0 {print}\' FILE
但是sed可以做到:
sed -i \'/^[0-9][0-9]*,[0-9][0-9]*,/d\' FILE
    ,
sed -iE \'/^([^,]+,){2} 0,/d\' file
用explain.py解释:
sed -iE \'/^([^,/d\' file
\\_/  ||  ||| || || \\_/ | |
 |   ||  ||| || ||  |  | \\- delete command
 |   ||  ||| || ||  |  |
 |   ||  ||| || ||  |  \\- followed by blank zero komma
 |   ||  ||| || ||  |
 |   ||  ||| || ||  \\- two times this inner pattern
 |   ||  ||| || ||
 |   ||  ||| || |\\- followed by a comma
 |   ||  ||| || |
 |   ||  ||| || \\- at least one of them
 |   ||  ||| ||
 |   ||  ||| |\\- komma
 |   ||  ||| |
 |   ||  ||| \\- not
 |   ||  |||
 |   ||  ||\\- start of pattern,group of characters,which are
 |   ||  ||
 |   ||  |\\- at begin of line
 |   ||  |
 |   ||  \\- start of pattern for delete command
 |   ||
 |   |\\- Extended regexp (parenthesis and braces without masking)
 |   |
 |   \\- inplace changes
 |
 \\- run sed
    ,使用就地编辑进行awk(类似于sed -i)
awk \'$3!=\"0,\"{print $0>FILENAME}\' file
红宝石(1.9+)
ruby -ane \'print unless $F[2]==\"0,\" \' file