SatisfyMyStruggles has asked for the wisdom of the Perl Monks concerning the following question:

I get the following error message: Error: can't read /var/log/log20098Message's no file or directory I think the problem has to do with the apostrophe s but unsure how to fix it after attempting to.. In this case the $file variable contains log20098Message's

system "sed -n -e '/log-passed/,/log-end/p' /var/log/app1/$file";

Replies are listed 'Best First'.
Re: Escape the apostrophe in sed command in perl script
by roboticus (Chancellor) on Jun 06, 2013 at 00:20 UTC

    SatisfyMyStruggles:

    It doesn't look like that's the line of code giving you the error, since the filename you gave doesn't match the pattern in the statement.

    You may as well use perl instead of sed anyway. Printing lines between two strings in a file is as easy as:

    while (<$FH>) { print if /log-passed/ .. /log-end/; }

    ...roboticus

    When your only tool is a hammer, all problems look like your thumb.

Re: Escape the apostrophe in sed command in perl script
by rjt (Curate) on Jun 06, 2013 at 00:41 UTC

    You can try to escape the apostrophe, but due to the inherent pain in the butt and security considerations due to trying to escape every special shell metacharacter, I would recommend using the list call to system instead:

    no warnings 'qw'; # Silence comma warning in qw my $foo = "foo'bar'"; system qw(echo sed -n -e /log-passed/,/log-end/p), "/var/log/app1/$foo +"; __END__ sed -n -e /log-passed/,/log-end/p /var/log/app1/foo'bar'

    The reason this works is that when system() is called with a single scalar containing metacharacters, that expression is passed to the shell, which will interpret shell metacharacters such as quotes, output redirection, semicolons, etc. However when system() is called with a list, Perl bypasses the shell and invokes the command directly, passing each additional list item as arguments to the command, so there is no shell involved at all, and, hence, no shell metacharacters.