LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - General (https://www.linuxquestions.org/questions/linux-general-1/)
-   -   using sed with parentheses in perl (https://www.linuxquestions.org/questions/linux-general-1/using-sed-with-parentheses-in-perl-344510/)

beebop 07-18-2005 11:45 PM

using sed with parentheses in perl
 
I'm working on converting a bash script to perl. But for some reason, perl does not like my parentheses. Here's my perl code:

#!/usr/bin/perl
sub main
{
system "for i in `ls`; do mv \$i `echo \$i | sed '/mp3\$/ s#\(^[0-9]\{2\}\)\([0-9a-zA-Z]\+\)#\1-\2#'`; done"; # <-- this is a continuation of the line above
}
&main();

First a brief explanation of what it does: It goes through every file in the current directory (hence the "for i in ls") and renames that file. You can see the mv command buried in there, the first argument being the original file name ($i) and the second arg being the renamed file. A sample file would be 01Artist-Song.mp3. After running the script, the file would be 01-Artist-Song.mp3 where the difference is the added dash between 01 and Artist.

The problem is in the sed command. In Bash, the first parentheses group is named 1 (which will be the first two digits), and the second is named 2 (which is the rest of the filename, not including the .mp3). I reuse those groups in the second part of sed, but in my perl script, the parentheses are not recognized. sed skips the replacement leaving the filename the same, and mv tries to move the old filename to the same filename resulting in an error for each file:

mv: `01PaulSimon-TheBoyInTheBubble.mp3' and `01PaulSimon-TheBoyInTheBubble.mp3' are the same file.

I have a lot of bash scripts I'd like to convert to perl and the 'system' perl command seemed like an easy fix. Maybe not....

Harmaa Kettu 07-19-2005 02:16 AM

Quote:

I have a lot of bash scripts I'd like to convert to perl and the 'system' perl command seemed like an easy fix. Maybe not....
What is the point of converting them if you only run shell commands from the converted versions?

Here is a better solution for this one:
Code:

foreach my $file (glob "*.mp3")
{
  if($file =~ /^(\d+)([^\d-].*)/)
  {
    rename $file, "$1-$2";
  }
}


beebop 07-21-2005 10:41 PM

<quote>What is the point of converting them if you only run shell commands from the converted versions?</quote>

Hehe, good question. I really like the option feature in perl. I'm including -h tags so I can actually remember what the hell my scripts mean, as well a a quick usage reference.

I guess I ~could~ rewrite all my scripts in perl. Probably easier in the long run...

Thanks for the code. It's a lot easier to read! This

if($file =~ /^(\d+)([^\d-].*)/)

is new to me. =~ is a "string equal" or something? Why not use ==? or -e?


All times are GMT -5. The time now is 02:03 PM.