I need to replace the whole line with sed
if it matches a pattern. For example if the line is 'one two six three four' and if 'six' is there, then the whole line should be replaced with 'fault'.
Find and replace text within a file using sed command Use Stream EDitor (sed) as follows: sed -i 's/old-text/new-text/g' input. txt. The s is the substitute command of sed for find and replace.
The s command (as in substitute) is probably the most important in sed and has a lot of different options. The syntax of the s command is ' s/ regexp / replacement / flags '.
Just add the line number before: sed '<line number>s/<search pattern>/<replacement string>/ . Note I use . bak after the -i flag. This will perform the change in file itself but also will create a file.
The 'sed' command is used to replace any string in a file using a bash script. This command can be used in various ways to replace the content of a file in bash. The 'awk' command can also be used to replace the string in a file.
You can do it with either of these:
sed 's/.*six.*/fault/' file # check all lines sed '/six/s/.*/fault/' file # matched lines -> then remove
It gets the full line containing six
and replaces it with fault
.
Example:
$ cat file six asdf one two six one isix boo $ sed 's/.*six.*/fault/' file fault asdf fault fault boo
It is based on this solution to Replace whole line containing a string using Sed
More generally, you can use an expression sed '/match/s/.*/replacement/' file
. This will perform the sed 's/match/replacement/'
expression in those lines containing match
. In your case this would be:
sed '/six/s/.*/fault/' file
What if we have 'one two six eight eleven three four' and we want to include 'eight' and 'eleven' as our "bad" words?
In this case we can use the -e
for multiple conditions:
sed -e 's/.*six.*/fault/' -e 's/.*eight.*/fault/' file
and so on.
Or also:
sed '/eight/s/.*/XXXXX/; /eleven/s/.*/XXXX/' file
Above answers worked fine for me, just mentioning an alternate way
Match single pattern and replace with a new one:
sed -i '/six/c fault' file
Match multiple pattern and replace with a new one(concatenating commands):
sed -i -e '/one/c fault' -e '/six/c fault' file
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With