Sed: Find and Replace The Whole Line [ Regex ]

You can use the sed command to find and replace the whole line using a regular expression (regex). The basic syntax is as follows:

sed 's/<regex to match>/<replacement string>/g' <input file>

Where <regex to match> is the pattern you want to search for, and <replacement string> is the string you want to replace it with. The g at the end of the sed command is used to perform a global search and replace, so all matches in the input file will be replaced.

Here is an example that replaces the whole line containing the word “error” with the string “no error”:

sed 's/^.*error.*$/no error/g' input_file.txt

In this example, the ^.*error.*$ regex matches any line that contains the word “error” anywhere. The ^ and $ characters in the regex specify the start and end of a line, so only whole lines will be matched. The .* before and after the word “error” matches any characters before and after the word, so that the whole line will be replaced.

If you want to modify the file in place, you can use the -i option:

sed -i 's/^.*error.*$/no error/g' input_file.txt

Note: The -i option creates a backup file with the extension .bak by default. If you don’t want to keep a backup, you can use the -i '' option instead.

Leave a Comment