Replace Strings in Multiple Files

“sed” command can be used for replacing strings in a file. For example, you can use the command below to replace “Apple” with “Orange” in fruits.txt file.

$ sed -i".bkp" -e "s/Apple/Orange/g" fruits.txt

Parameter “-i” makes the target file overwritten, but a backup is created by specifying a string (“.bkp” for this case) after “-i” whose filename has the string as suffix.

You can combine “xargs” and “find” command with “sed” to process multiple files at once. “find” is for searching files and “xargs” is for executing any commands using values from standard input as parameters. For example, you can use the command below to replace “Apple” with “Orange” in all files in current directory.

$ find . -maxdepth 1 -type f | xargs sed -i".bkp" -e "s/Apple/Orange/g"

Leave a Reply

Required fields are marked *.


This site uses Akismet to reduce spam. Learn how your comment data is processed.

Top