【发布时间】:2014-10-12 22:06:58
【问题描述】:
我正在尝试找出对不在注释分隔符之后的字符串进行 grep 的最佳方法。考虑以下文件“test_file”:
#测试这个 1 #测试这个 2 测试这个 3 测试这个 4 # 我的测试这 5 # 我的测试这 6 我的测试这 7 我的测试这 8 测试这个 9 # 我的测试这个 9 this 10 # 我的测试 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" 是如何工作的,这会是我想要的吗?
【问题讨论】:
-
那么你想要哪几行? 3、4、5、8、9?
-
只是让你知道。
sed语句正在删除任何前导空格,grep正在寻找以非#(零个或多个)字符开头的行,后跟单词test。 -
@skamazin ahhh 我现在明白它在做什么了。谢谢!