How to replace text in all files in a folder?

I need to update one parameter in a large set of XML files. I read and use one perl line on the Windows command line, I can get it to do file permissions at a time, but I'm struggling to get perl to do all the files at once.

perl -pi.bak -e "s/(\d+\.\d+E-\d+)/2.2E-6/g;" test.xml 

This works, however, when I try to change it to something like

 perl -pi.bak -e "s/(\d+\.\d+E-\d+)/2.2E-6/g;" *.xml 

I get "Can't open * .xml: Invalid argument"

 perl -pi.bak -e "s/(\d+\.\d+E-\d+)/2.2E-6/g;" .xml 

Gives me "Unable to open .xml: No such file or directory"

I tried to figure out if I could call it from another perl script using system (), however this does not seem to take into account the use of quotes and may not be the best way to do this.

Summary:

Problem. I have a large number of XML files inside which I want to change one parameter. I should be able to do this on a Windows machine, and ideally I would like to work on a solution that would allow me to automate this in a script so that I can cycle through numerous parameter substitutions (with a separate program that accepts the files that are being called. xml as input between replacements).

Thanks for any help you can offer.

+4
source share
6 answers

Try the following:

for / r% I'm in (* .xml) do perl -pi.bak -e "s / (\ d +. \ d + E- \ d +) / 2.2E-6 / g;" % I AM

+3
source

When I like this, I usually use the following pattern:

ls *.xml | xargs perl -i.bak -p -e "s/<search>/<replace>/g"

On Windows, you can use the following template:

for %f in (*.xml) do perl -i.bak -p -e "s/<search>/<replace>/g" "%f"

See Perl 5 for an example: using the -n and -p options for more details.

+3
source

You can use the for loop in the .cmd script. Sort of:

 for %%a in (*.xml) do ( perl -i.bak ... %%a ) 

The cmd.exe link is convenient here.

+3
source

use File::Find;

UPDATE: you can use this single line layer:

perl -we 'use File::Find; my $dir = shift; find (sub { $_=~ /\.xml$/i and system @ARGV, $_ }, $dir)' <dir> <other-one-liner>

+1
source

The problem is that the Windows excuse for the shell does not flush the file name (* .xml extension to all files with the .xml extension).

Since the shell does not do this for you, you must do it yourself.

This is easy to do in Perl, but it needs to be done before the "internal" code begins, so put it in a BEGIN block:

 perl -pi.bak -e "BEGIN{@ARGV=glob shift} s/(\d+\.\d+E-\d+)/2.2E-6/g;" *.xml 
+1
source

find . -type f -name *.xml | xargs perl -pi.bak -e "s/(\d+\.\d+E-\d+)/2.2E-6/g; find . -type f -name *.xml | xargs perl -pi.bak -e "s/(\d+\.\d+E-\d+)/2.2E-6/g; "

all files will be transferred. (recursively) by matching .xml with the perl command, one at a time.

0
source

Source: https://habr.com/ru/post/1344268/


All Articles