PDA

View Full Version : How to search and replace in Linux files



Fli
09-09-2016, 10:37 AM
Before doing search and replace, backup data.

search and replace in file:
sed -i "s|search|replace|g" file

search and replace in the variable
$variable="$(echo "$variable"|sed "s|search|replace|g")

search and replace only if line contains defined phrase:
sed -i "/Next/ s|#||g" file
(replace # by nothing (remove) on the line that contains Next)

search and replace multiple phrases in file:
sed -i "s|search|replace|g;s|search2|replace2|g"

Preview changes instead of writing them into file:
cat "filename"|sed "s|search|replace|g"

search and replace in all directory files containing username .php:
for file in $(find -A1 /path/to/filesdir/|grep -v "./"|grep ".php");do sed -i "s|search|replace|g" $file;done

NOTES:

backup before doing search&replace

one can use / or other character instead of |

some characters like slash and quotation mark needs to be escaped by backslash, example: sed -i "s|<img src=\"\" \/>|<img src=\"url\" \/>|g" file

RuskinF
08-05-2020, 12:23 PM
grep is the most important command to use to replace data in files in Linux.
I will let you know what you can do to use grep command.

grep is a utility for searching for strings through multiple text files. Here I'm invoking it with the following parameters:

R — perform a recursive search, also across symbolic links;
i — case-insensitive search
I — skip binary files. We are working with text, afer all;
l — print results as a simple list of file names. This is needed for the next command.

Apart from that, you need sed.

sed is a glorious Unix utility that transforms text. In the current snippet I'm using it to replace text with the following parameters:

i — replace in file. Remove it for a dry run mode;
s/search/replace/g — this is the substitution command. The s stands for substitute (i.e. replace), the g instructs the command to replace all occurrences.


FunFact: Azure Windows 10 (https://www.apps4rent.com/windows-virtual-desktop-azure) is a virtual desktop based on Azure platform which itself is based on Linux kernel.