简体   繁体   中英

How to replace a string in multiple files?

I want to replace a string which occurs in several files. For a single file I am able to do using unix command :

sed 's/error("/printf( "ERROR : /g' all_reset_test.c > new_reset/all_reset_test.c 

which replaces all 'error("' with 'printf( "ERROR : ' in this file.

But I have over 100 files for which I need to do this. I am looking for how to run this command for all files at once in either a perl or a python script.

例如,如果文件的扩展名为.txt,则可以使用以下命令:

%> perl -pi -e 's/error("/printf( "ERROR : /' *.txt

You can use sed's option -i

Quoting from sed's manpage:

-i[SUFFIX], --in-place[=SUFFIX]

      edit files in place (makes backup if extension supplied)

If you omit the SUFFIX sed will not create a backup before modifying the file.

In your case this

sed -i 's/error("/printf( "ERROR : /g' *.c

should do the job (without pyhton, perl, or a bash loop).

You can use a simple bash for loop to apply this logic to all of your files:

for f in $(ls *.c); do 
   sed 's/error("/printf( "ERROR : /g' ${f} > new_reset/${f}
done

The $(ls *.c) portion should be replaced by whatever ls command will select the files that you want to apply the sed command to.

Just wrap your sed command in a for cycle:

for file in $(cat file_list)
do
    sed 's/error("/printf( "ERROR : /g' $file > new_reset/$file
done

Of course, the list of files to edit can be obtained in multiple ways:

for file in $(ls *.c)  # if the files are in the same folder
do
    sed 's/error("/printf( "ERROR : /g' $file > new_reset/$file
done

Or

for file in $(find -type f -name '*.c')
do
    sed 's/error("/printf( "ERROR : /g' $file > new_reset/$file
done

You can iterate over files in the shell eg this finds all the .txt files in the subdirectories below the current directory. Each file is available in $f

for f in $(find . -name \*.txt); do
   # run my sed script for $f
done

There are numerous options for iterating over a set of files using bash. See here for some options. If you filenames have spaces, you will have to be careful, and this SO question/answer details some options.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM