How to find and replace specified string with sed in linux/unix

In the previous article, we introduced how to use the sed command to replace multiple patterns.

This article is an extension of the previous article, we will share with you how to find and replace the specified string.

The following is the content of the text file used in this test. We will use the Linux command line tool to find and replace its content.

This is a test file.

Use the grep command to match content 
and the sed command to replace content.

Use the find command to find the file 
and use the sed command to replace the content.

Use the grep command and sed command to search and replace

In the following example, we will use the grep command pattern search the content in the current directory, and use sed to replace the content of the file through the pipeline.

➜ grep -Rl 'replace the content' . | xargs sed 's/replace the content/replace/g'

Command options description:
* grep -l Only the names of files containing selected lines are written to standard output.
* grep -R, -r Recursively search subdirectories listed.
* xargs Converts pipe or standard input (stdin) data into command-line arguments and execute utility

Use the find command and sed command to find files and replace

In the following example, we first use the find command to find out all the files in the current directory (of course, if you know the file format of the content you need to replace, you can do pattern matching here), and use sed to replace the content of the file through the pipeline .

➜ find . -type f -name "*.log" -exec sed 's/replace the content/replace/g' {} \;

# OR

➜ find . -type f -name "*.log" | xargs sed 's/replace the content/replace/g'

But usually we also use the grep command after the find command, so that accurate queries can be achieved.

For example, in the following example, when there are multiple .log files in the directory, it is not very friendly to use the above command. At this time, we can use grep to perform an accurate search in the result set of the find command.

➜  find . -type f -name "*.log" | xargs grep -l 'replace the content' | xargs sed 's/replace the content/replace/g'

Add a Comment

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