【问题标题】:in ksh/grep: finding a pattern not after the comment marker在 ksh/grep 中:找到不在注释标记之后的模式
【发布时间】: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 我现在明白它在做什么了。谢谢!

标签: regex bash sed grep ksh


【解决方案1】:

对包含“test”且前面没有# 字符的行进行Grep:

grep -n '^[^#]*test'  

匹配行首 (^),后跟任意数量的不是“#”的字符 ([^#]*),然后是“test”。

【讨论】:

  • 啊,这很有意义。不知道为什么我的大脑无法解析它在说什么。谢谢。
【解决方案2】:

您只能使用 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

【讨论】:

    猜你喜欢
    • 2013-10-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-28
    相关资源
    最近更新 更多