2

I'm having trouble executing a Perl script through the Unix shell using Perl's system command.
I've had more complex regex commands I had to adjust accordingly to convert from Unix to Perl, and they're working fine, but I can't seem to figure out what's missing here.
I've tested with Mobaxterm v7.1 and Putty 0.60.

I have a file (file.txt):

23445 dir1/dir2/dir3
21343 dir1/dir2/dir3/dir4/file.B2
54322 dir1/dir2/dir3/file3.P
53223 dir1/dir2/dir3/dir4/dir5
23412 dir1/dir2/dir3/dir4/dir5/file5.xsd
54166 dir1/dir2/file6.AB
64544 dir1/dir2/fil7.ABE

From this file I'm trying to grep only the lines with files (exclude directories: lines 1 and 4), and store them in a new file:

system("grep '^.*\.[a-zA-Z0-9][a-zA-Z0-9]*\$' file.txt > file2.txt");

file2.txt doesn't change from file.txt and still contains the directories.

However, this command works through Unix shell (without the backslash before the $):

grep '^.*\.[a-zA-Z0-9][a-zA-Z0-9]*$' file.txt > file2.txt

file2.txt output:

21343 dir1/dir2/dir3/dir4/file.B2
54322 dir1/dir2/dir3/file3.P
23412 dir1/dir2/dir3/dir4/dir5/file5.xsd
54166 dir1/dir2/file6.AB
64544 dir1/dir2/fil7.ABE

I have to escape the $ character in the Perl system command of course so that Perl doesn't read it as an unknown string. Other than that, what needs to be adjusted in the system command?

2

In double quotes, you need to backslash backslashes, i.e. double the backslash before the dot.

system("grep '^.*\\.[a-zA-Z0-9][a-zA-Z0-9]*\$' file.txt > file2.txt");
#                ^
#                |
#              Here.
  • 1
    Could you flesh this out a little? Perhaps add a working example? – terdon Oct 6 '14 at 15:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.