【问题标题】:Find first occurrence of a string after the first occurrence of another string with bash使用 bash 在第一次出现另一个字符串后查找第一次出现的字符串
【发布时间】:2019-05-31 14:28:35
【问题描述】:

我有一个看起来像这样的输入文件,我想要第一次出现的单词,但只有在第一次出现 special 之后

只有数字在那里,所以我知道我得到了正确的字符串

编辑:我意识到字符串有 /'s 很重要

words/and/stuff #1
words/more #2
some/other/words #3
special/this #1
words/i/need/you/i.really.need.you #4
special/cool #2 
words/random #5

我试图在找到“特殊”的第一次出现后找到“单词”的第一次出现

输出应该是

words/i/need/you/i.really.need.you #4

我尝试了以下方法

grep -m1 special file | grep -m1 words file 

awk 'NR==1,/special/ && NR==1,/words/ {print $0}' file 

【问题讨论】:

  • 你几乎拥有它...grep -A 99999 special file | grep -m1 words
  • @MarkSetchell 哇!!!!这很简单直接!!!!我最终会使用它。
  • 我正在学习制作模拟输入文件是多么无知。我将开始放置文字输入文件以避免双方都感到头疼。这实际上是针对一个 xml 文件的,并且 grep 命令返回两个 greps 而不仅仅是后者,但我可以从那里解决它可能有点多余。但不好玩。

标签: awk grep


【解决方案1】:

试试:

$ awk '/special/{f=1} f && /words/ {print; exit}' file 
words/i/need/you/i.really.need.you #4

它是如何工作的:

  • /special/{f=1}

    如果当前行匹配special,则将变量f设置为1

  • f && /words/ {print; exit}

    如果f 非零且当前行匹配words,则打印当前行并退出。

带斜线的单词

如果您要匹配的单词不仅被斜杠包围,而且包含斜杠,则相同的代码可以工作。只需要避开斜线即可。例如,如果我们在special 之后查找单词words/i/need

$ awk '/special/{f=1} f && /words\/i\/need/ {print; exit}' file 
words/i/need/you/i.really.need.you #4

【讨论】:

  • 非常抱歉后来意识到我有 / 会影响代码
  • @goosegoose 感谢您的通知。使用更新的输入文件,这里的相同代码仍然有效。
【解决方案2】:

请您尝试关注一下。

awk '
$0=="words"{
  count++
  if(special_count==1){
    print "String words count is: "count
    exit
  }
}
/special/{
  special_count++
}
'  Input_file

【讨论】:

  • 非常抱歉后来意识到我有 / 会影响代码
  • @goosegoose,抱歉我没听懂;如果您的字符串不是words,那么在我的代码中将其更改为word?
【解决方案3】:

快速专用sed脚本

你可以为此使用

sed -e  '/special/,${ /word/q;d };d' file

将从您的示例中输出:

words #4
  • 从包含 special 的行到输入结束,

    • 如果行包含word,则退出
    • 否则删除行。
  • 否则,删除行。

,作为你关于bash的问题标题:

w1=false
while read line ;do
    if [ "$line" ] ;then
        if $w1 && [ -z "${line//*words*}" ] ;then
            echo $line
            break
        fi
        if [ -z "${line//*special*}" ] ;then w1=true ;fi
    fi
done <file

【讨论】:

  • 非常抱歉后来意识到我有 / 会影响代码
  • @goosegoose 没关系!你试过这个吗?如果需要,您可以使用 / 以外的其他东西!或者逃离他们:/special\/cool/
  • @goosegoose 我刚刚测试了您修改后的输入!我的代码仍然有效!
猜你喜欢
  • 2017-12-25
  • 2018-02-05
  • 2022-01-13
  • 1970-01-01
  • 1970-01-01
  • 2019-10-23
  • 2015-06-13
  • 2011-12-19
  • 2015-06-08
相关资源
最近更新 更多