How do you “debug” a regular expression with sed?

后端 未结 8 1570
日久生厌
日久生厌 2021-01-31 08:19

I\'m trying to use a regexp using sed. I\'ve tested my regex with kiki, a gnome application to test regexpd, and it works in kiki.

date: 2010-10-29          


        
8条回答
  •  日久生厌
    2021-01-31 09:16

    If you want to debug a sed command, you can use the w (write) command to dump which lines sed has matched to a file.

    From sed manpages:

    Commands which accept address ranges

    (...)

    w filename

    Write the current pattern space to filename.


    Applying to your question

    Let's use a file named sed_dump.txt as the sed dump file.

    1) Generate the sed dump:

    sed "/author:\s[0-9]{11};/w sed_dump.txt" /tmp/test_regex.txt
    

    2) Check file sed_dump.txt contents:

    cat sed_dump.txt
    

    Output:

    It's empty...

    3) Trying to escape '{' regex control character:

    sed "/author:\s[0-9]\{11\};/w sed_dump.txt" /tmp/test_regex.txt
    

    4) Check file sed_dump.txt contents:

    cat sed_dump.txt
    

    Output:

    date: 2010-10-29 14:46:33 -0200; author: 00000000000; state: Exp; lines: +5 -2; commitid: bvEcb00aPyqal6Uu;

    Conclusion

    In step 4), a line has been matched, this means that sed matched your pattern in that line. It does not guarantee the correct answer, but it's a way of debugging using sed itself.

提交回复
热议问题