How to replace strings in files in the Linux command line

Replace strings in single file or multiple files. I believe that we will encounter it in daily development.

So do you know how to replace strings in single file or multiple files using the linux command line.

Replace a string in a file

A file replaces a string.

You can usually use the linux vim/vi command to open the file and replace a string, or you can use the linux sed command to replace it.

Use the linux vim command

Use the vim/vi command to open a single file, search for the string to be replaced and replace it, or use regular batch replacement.

➜  vim test.log
# Enter the following command:
# :%s/string/character/g
# save file 
# :x

➜  cat test.log
Replace a character in a file.
Replace a character in a file.
Replace a character in a file.
Replace a character in a file.
Replaces multiple characters in a file.
This character needs to be replaced.
➜ 

Use the linux sed command

Using the sed command, you can directly replace the contents of a file without opening it.

➜  sed -i 's/character/string/g' test.log

Replace a string in multiple files

Replace multiple files with the sed command

Replace the string “string” with “character” in all *.log files in the current directory

➜  sed -i 's/string/character/g' *.log

Find and replace strings using grep command and sed command

Find all files in the current directory containing the string “string” and replace the string “string” with “character”

➜  grep -l "string" *  | xargs sed -i "s/string/character/g"

grep -l:  –print-with-matches, prints the name of each file that has a match.
xargs: transform the STDIN to arguments.
sed -i: edit files in place, without backups.

OK.

At this time, we already know how to use linux commands to replace strings in one or more files. We also know how to replace multiple files in batches, and how to specify the replacement of multiple file strings.

Add a Comment

Your email address will not be published. Required fields are marked *