[英]in ksh/grep: finding a pattern not after the comment marker
我试图找出最好的方法来grep的字符串不在注释定界符之后。 考虑以下文件“ test_file”:
#test this 1 #test this 2 test this 3 test this 4 # my test this 5 # my test this 6 my test this 7 my test this 8 test this 9 # my test this 9 this 10 # my test this 10
我想grep进行“测试”,但只返回第3、4、7、8和9行。
我可以通过以下方法获得此结果:
sed -e 's/^[ ]*//' test_file | grep -n "^[^#]*test"
3:test this 3
4:test this 4
7:my test this 7
8:my test this 8
9:test this 9 # my test this 9
但是我不确定它是如何工作的,因此我担心它可能会带来意想不到的后果。 在星号之前添加一个点(我认为这可能是这样做的方式)不起作用:
sed -e 's/^[ ]*//' test_file | grep -n "^[^#].*test"
7:my test this 7
8:my test this 8
9:test this 9 # my test this 9
10:this 10 # my test this 10
我能够做的另一种解决方案是简单地使用sed删除井号和grep之后的所有文本以进行“测试”,这是直接且实用的。 但是我很好奇-前grep -n "^[^#]*test"
工作原理是什么?
Grep查找包含“ test”且#
其前面没有#
字符的行:
grep -n '^[^#]*test'
它与行的开头( ^
)相匹配,后跟不是 '#'( [^#]*
)的任意数量的字符,后跟“ test”。
您只能使用grep执行此操作:
grep -n '^[^#]*test' file
3:test this 3
4: test this 4
7:my test this 7
8: my test this 8
9:test this 9 # my test this 9
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.