Linux Find and Replace

Find and replace with sed in directory and sub directories

Your find should look like that to avoid sending directory names to sed:

find ./ -type f -exec sed -i -e 's/apple/orange/g' {} \;

linux command to find files and replace with another file

Assuming you have the replacement file in your home directory (~), you can use find to do the replacing. This will find all boom.txt files and replace them with the replace.txt file (keeping the boom.txt name).

find . -name "boom.txt" -exec cp ~/replace.txt {} \;

How to replace a string in multiple files in linux command line

cd /path/to/your/folder
sed -i 's/foo/bar/g' *

Occurrences of "foo" will be replaced with "bar".

On BSD systems like macOS, you need to provide a backup extension like -i '.bak' or else "risk corruption or partial content" per the manpage.

cd /path/to/your/folder
sed -i '.bak' 's/foo/bar/g' *

Using grep and sed to find and replace a string

You can use find and -exec directly into sed rather than first locating oldstr with grep. It's maybe a bit less efficient, but that might not be important. This way, the sed replacement is executed over all files listed by find, but if oldstr isn't there it obviously won't operate on it.

find /path -type f -exec sed -i 's/oldstr/newstr/g' {} \;

Find and replace inside a string variable using sed command - shell scripting

You don't use -i, as that's for changing a file in place. If you want to replace the value in the variable, you need to reassign to it.

find and replace command for whole directory

This will replace in all files. It can be made more specific if you need only a specific type of file. Also, it creates a .bak backup file of every file it processes, in case you need to revert. If you don't need the backup files at all, change -i.bak to -i.

find /path/to/directory -type f -exec sed -i.bak 's/oldword/newword/g' {} \;

To remove all the backup files when you no longer need them:

find /path/to/directory -type f -name "*.bak" -exec rm -f {} \;

Find and replace in shell scripting

Sure, you can do this using sed or awk. sed example:

sed -i 's/Andrew/James/g' /home/oleksandr/names.txt

Linux/Unix Replacing a pattern in a string and saving to a new file with sed

You can try this sed command

sed 's/,\(.*china\)/,Tomas_proxy.lt\/\1/' FileName

or

sed 's/,\(.*china\)/,Tomas_proxy.lt\/\1/' FileName > NewFile

or

sed  -i.bak 's/,\(.*china\)/,Tomas_proxy.lt\/\1/' FileName 


Related Topics



Leave a reply



Submit