When working with text files, you’ll often need to find and replace strings of text in one or more files.
So let’s bind some commands like:
The Linux grep command is a string and pattern matching utility that displays matching lines from multiple files. It also works with the piped output from other commands.
The grep command is famous in Linux and Unix circles for three reasons. Firstly, it is tremendously useful. Secondly, the wealth of options can be overwhelming. Thirdly, it was written overnight to satisfy a particular need.
grep -RiIl ‘search’ Quick grep explanation:
1 2 3 4 -R - recursive search -i - case-insensitive -I - skip binary files (you want to text, right?) -l - print a simple list as output. Needed for the other commands
sed is a stream editor. It can perform basic text manipulation on files and input streams such as pipelines. With sed, you can search, find and replace, insert, and delete words and lines. It supports basic and extended regular expressions that allow you to match complex patterns.
1 sed -i 's/SEARCH_REGEX/REPLACEMENT/g' INPUTFILE
Quick sed explanation:
- -i - By default, sed writes its output to the standard output. This option tells sed to edit files in place. If an extension is supplied (ex -i.bak), a backup of the original file is created.
- s - The substitute command, probably the most used command in sed. / / / - Delimiter character. It can be any character but usually the slash (/) character is used.
- SEARCH_REGEX - Normal string or a regular expression to search for.
- REPLACEMENT - The replacement string.
- g - Global replacement flag. By default, sed reads the file line by line and changes only the first occurrence of the SEARCH_REGEX on a line. When the replacement flag is provided, all occurrences are replaced.
INPUTFILE - The name of the file on which you want to run the command. Need to string some Linux commands together, but one of them doesn’t accept piped input? xargs can take the output from one command and send it to another command as parameters.
the full code of replacing a string in multiple files in Linux command line
1 grep -RiIl 'research' | xargs sed -i 's/RESEARCH/REPLACEMENT/g'
Hi there 👋 Support me!
Life is an echo—what you send out comes back.