tags:

views:

1386

answers:

6

Within a set of large files, I need to replace all occurrences of "\" with "\\". I'd like to use Perl for this purpose. Right now, I have the following:

perl -spi.bak -e '/s/\\/\\\\/gm' inputFile

This command was suggested to me, but it results in no change to inputFile (except an updated timestamp). Thinking that the problem might be that the "\"s were not surrounded by blanks, I tried

perl -spi.bak -e '/s/.\\./\\\\/gm' inputFile

Again, this had no effect on the file. Finally, I thought I might be missing a semicolon, so I tried:

perl -spi.bak -e '/s/.\\./\\\\/gm;' inputFile

This also has no effect. I know that my file contains "\"s, for example in the following line:

("C:\WINDOWS\system32\iac25_32.ax","Indeo audio)

I'm not sure whether there is a problem with the regex, or if something is wrong with the way I'm invoking Perl. I have a basic understanding of regexes, but I'm an absolute beginner when it comes to Perl.

Is there anything obviously wrong here? One thing I notice is that the command returns quite quickly, despite the fact that inputFile is ~10MB in size.

+1  A: 

How about this it should replace all \ with two \s.

s/\\/\\\\/g
Copas
You do \ is the escape character so \\ is treated a a literal \
Copas
A: 
perl -spi.bak -e 's/.\\./\\\\/gm;' inputFile

maybe? Why did you type that leading /?

alamar
+5  A: 

The hard part with handling backslashes in command lines is knowing how many processes are going to manipulate the command line - and what their quoting rules are.

On Unix, under any shell, the first command line you show would work.

You appear to be on Windows, and there, you have the DOS command 'shell' to deal with.

I would put the replacement into a file and pass that to Perl:

#!/bin/perl -spi.bak
s/\\/\\\\/g;

That should do the trick - save as 'subber.pl' and then run:

perl subber.pl file1 ...
Jonathan Leffler
A: 
perl -pi -e 's/\\/\\\\/g' inputfile

will replace all of them in one file

Milan Ramaiya
Oh, and inputfile can be a pattern, so this can modify all your files in one shot
Milan Ramaiya
+1  A: 

this

s/\\/\\\\/g

works for me

You've got a renegade / in the front of the substitution flag at the beginning of the regex

don't use

.\\.

otherwise it will trash whatever's before and after the \ in the file

whatsisname
A: 

You appear to be on Windows, and there, you have the DOS command 'shell' to deal with.

Hopefully I am not splitting hairs but Windows hasn't come with DOS for a long time now. I think ME (circa 1999/2000) was last version that still came with DOS or was built on DOS. The "command" shell is controlled by cmd.exe since XP (a sort of DOS simulation), but the affects of running a perl one-liner in a command shell might still be the same as running them in a DOS shell. Maybe someone can verify that.