How do you use sed from Perl?

前端 未结 10 521
渐次进展
渐次进展 2021-01-18 01:14

I know how to use sed with grep, but within Perl the below fails. How can one get sed to work within a Perl program?

c         


        
10条回答
  •  一向
    一向 (楼主)
    2021-01-18 01:23

    It is easier to use Perl than to use grep and sed; see another answer.

    Your code failed because Perl messed with the backslashes in your sed code. To prevent this, write your sed code in 'a single-quoted Perl string', then use \Q$sedCode\E to interpolate the code into the shell command. (About \Q...E, see perldoc -f quotemeta. Its usual purpose is to quote characters for regular expressions, but it also works with shell commands.)

    my $fileToProcess = "example.txt";
    my $sedCode = 's/^\([0-9]*\)[:].*/\1/p';
    chomp(my @linenumbers =
          `grep -n "textToFind" \Q$fileToProcess\E | sed -n \Q$sedCode\E`);
    printf "%s\n", join(', ', @linenumbers);
    

    Given example.txt with

    this has textToFind
    this doesn't
    textToFind again
    textNotToFind
    

    the output is 1, 3.

提交回复
热议问题