开发者

Regex multiple line match recursively in subfolders (one liner)

I currently use the following Perl one liner to match multiple lines in files recursively among subfolders. It works except that it forces you to use a . to match a \n. But I am in need to use \n because the . will also match any char.

Is there any way to do this with a Perl one liner ? How about one liners with other Linux programs ?

perl -i -pe 'BEGIN{undef $/;} s/FIND/REPLACE/smg' $(f开发者_高级运维ind "/PATH-TO-DIRECTORY" -name "*.html" -type f)

EDIT :

Regex: \thello world!....

Regex: \thello world!\n\n\n\n

Test example:


    hello world!


    hello world!
    foo


I created a tree of directories and files that would result in the situation below:

$ cat $(find a -type f)
EFabcd
EFbacA
QuuxQuuxr
Foobar
abcd

Then, using sed I think I got a solution for what you are looking for:

$ sed -n 'H;${x;s/d\nEF/FOO/;p;}' $(find a -type f)

How does it work? First, we suppress the output of sed with -n. Then comes the command. For each line, we append a newline and the content of the line to the hold space:

H

At the end of the file, it bring the content of the hold space to the pattern space (where the replacement can be made):

x

After this, we have all the content of all the files treated as a sole line. Now we can replace a pattern which includes a new line as well, such as:

s/d\nEF/FOO/

Once the replacement applied, we print the result:

p

The result:

$ sed -n 'H;${x;s/d\nEF/FOO/g;p;}' $(find a -type f)

EFabcFOObacA
QuuxQuuxr
Foobar
abcd

(Note that there is an empty line at the beginning of the result. It is easy to repair as well, I believe.)

Is something like this what are you looking for?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜