How do you use sed from Perl?

前端 未结 10 515
渐次进展
渐次进展 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

    Anything you need to do with grep or sed can be done natively in perl more easily. For instance (this is roughly right, but probably wrong):

    my @linenumbers;
    open FH "<$fileToProcess";
    while (<FH>)
    {
       next if (!m/textToFind/);
       chomp;
       s/^\([0-9]*\)[:].*/\1/;
       push @lineNumbers, $_;
    }
    
    0 讨论(0)
  • 2021-01-18 01:23

    You can use

    perl -pe 's/search/replace/g'
    

    in place of

    sed 's/search/replace/'
    

    .. However ..

    Those are meant for command line or shell scripts. Since youre already in a perl script, the correct answer was given by "Paul Tomblin" above.

    Have fun, eKerner.com

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-01-18 01:29

    I'm surprised that nobody mentioned the s2p utility, which translates sed "scripts" (you know, most of the time oneliners) to valid perl. (And there's an a2p utility for awk too...)

    0 讨论(0)
  • 2021-01-18 01:29

    Supposedly Larry Wall wrote Perl because he found something that was impossible to do with sed and awk. The other answers have this right, use Perl regular expressions instead. Your code will have fewer external dependencies, be understandable to more people (Perl's user base is much bigger than sed user base), and your code will be cross-platform with no extra work.

    Edit: Paul Tomblin relates an excellent story in his comment on my answer. I'm putting it here to increase it's prominence.

    "Henry Spencer, who did some amazing things with Awk, claimed that after demoing some awk stuff to Larry Wall, Larry said he wouldn't have bothered with Perl if he'd known." – Paul Tomblin

    0 讨论(0)
  • 2021-01-18 01:29

    Edited: OK, I fixed it now.

    use File::Grep qw/fmap/;
    
    my @lineNumbers = fmap { /$pattern/ ? $_[1] : () } $fileToProcess;
    
    0 讨论(0)
提交回复
热议问题