sed rare-delimiter (other than & | / ?…)

后端 未结 8 2138
傲寒
傲寒 2020-12-17 17:42

I\'ve to apply the Unix command sed on a string (can contain #, !, /, ?, &, @ and all other characters) which can contains all types of

8条回答
  •  执笔经年
    2020-12-17 18:30

    You need the nested delimiter facility that Perl offers. That allows to use stuff like matching, substituting, and transliterating without worrying about the delimiter being included in your contents. Since perl is a superset of sed, you should be able to use it for whatever you’re used sed for.

    Consider this:

    $ perl -nle 'print if /something/' inputs
    

    Now if your something contains a slash, you have a problem. The way to fix this is to change delimiter, preferably to a bracketing one. So for example, you could having anything you like in the $WHATEVER shell variable (provided the backets are balanced), which gets interpolated by the shell before Perl is even called here:

     $ perl -nle "print if m($WHATEVER)" /usr/share/dict/words
    

    That works even if you have correctly nested parens in $WHATEVER. The four bracketing pairs which correctly nest like this in Perl are < >, ( ), [ ], and { }. They allow arbitrary contents that include the delimiter if that delimiter is balanced.

    If it is not balanced, then do not use a delimiter at all. If the pattern is in a Perl variable, you don’t need to use the match operator provided you use the =~ operator, so:

    $whatever = "some arbitrary string ( / # [ etc";
    if ($line =~ $whatever) { ... }
    

提交回复
热议问题