如何在不知道换行符的情况下跨多行grep长字符串

Tab*_*hka 1 bash grep

我想在文件中的多行中搜索特定字符串并获取找到匹配项的行。

但是,我的问题是,该文件包含一个很长的字符串,而不是单词,我想搜索这个长字符串的子序列。因此,我不能使用 pcregrep 而只能搜索 word1\nword2。因为我实际上想获取找到匹配项的行号,所以我不能只删除所有换行符...

这是我的文件的示例,我只是将匹配的字符串大写,以便您可以找到它:

要搜索的字符串:

gcbcdbfceebcfhfchaaccdgfcegffgedffaeaedcbaedhacebeeebcechbcbfeeccbdhcbfg
Run Code Online (Sandbox Code Playgroud)

要搜索的文件:

abcdeabcdeabcdeabcdeabcdeabcdeabcdeabcdeabcdeabcde
abcdeabcde***GCBCDBFCEEBCFHFCHAACCDGFCEGFFGEDFFAEAEDC
BAEDHACEBEEEBCECHBCBFEECCBDHCBFG***ggfbhbgcedabceedfa
fbaaechaabdbffbebecebaacfcfcdcggfchddcefbcbdegbbba
Run Code Online (Sandbox Code Playgroud)

你们中有人有一个简单的解决方案吗?

如果手头没有工具可以做到这一点,我只会编写一个简短的 python 脚本来做到这一点,但我想任何 bash 工具都会比这更有效......

编辑

非常感谢您的回答,如果知道换行符的位置,它们工作得很好。

但是,我很抱歉我的问题不准确。我的问题是,我不知道文件中的字符串中是否有换行符,甚至不止一个换行符,而且,我不知道它在哪里。我通过删除无意中插入的换行符来更正我的搜索字符串。

有没有办法允许在字符串的任何位置换行?

Nic*_*ton 5

我会用脚本来做到这一点sed。把它放在一个文件中,然后用sed -nf它来运行它。

:restart
/gcbcdbfceebcfhfchaaccdgfcegffgedffaeaedc$/{
    #   Found the first part, now discard it
    s/^.*$//
    #   Read a new line into the buffer
    N
    #   Discard the new line inserted by the N operation
    s/^\n//
    #   If next line isn't a match, start over
    /^baedhacebeeebcechbcbfeeccbdhcbfg/!b restart
    #   If it is a match, print the line number
    =
    }
Run Code Online (Sandbox Code Playgroud)

这是在bash. 请注意,它打印了匹配的第二行的行号。

bash-4.1$ cat sample.txt
abcdeabcdeabcdeabcdeabcdeabcdeabcdeabcdeabcdeabcde
abcdeabcde***gcbcdbfceebcfhfchaaccdgfcegffgedffaeaedc
baedhacebeeebcechbcbfeeccbdhcbfg***ggfbhbgcedabceedfa
fbaaechaabdbffbebecebaacfcfcdcggfchddcefbcbdegbbba
bash-4.1$
bash-4.1$ cat findmatch.sed
:restart
/gcbcdbfceebcfhfchaaccdgfcegffgedffaeaedc$/{
   #  Found the first part, now discard it
   s/^.*$//
   #  Read a new line into the buffer
   N
   #  Discard the new line inserted by the N operation
   s/^\n//
   #  If next line isn't a match, start over
   /^baedhacebeeebcechbcbfeeccbdhcbfg/!b restart
   #  If it is a match, print the line number
   =
   }
bash-4.1$
bash-4.1$ sed -nf findmatch.sed sample.txt
3
bash-4.1$
Run Code Online (Sandbox Code Playgroud)