In the following file:

semi1245  5465 and taxes ?>:"  foo 214 sdnfv 1>?<: Wed
dsfsdf  46 and gsdgsd blah and blah taxes   foo 214 sdnfv 1>?<: Wed sadfaads

I want to delete everything after foo (including foo) from every lines (If the line contains foo) .

My desired output:

semi1245  5465 and taxes ?>:" 
dsfsdf  46 and gsdgsd blah and blah taxes 

2 Answers 2


sed -i.bak 's/foo.*//' testfile.txt will be sufficient for this.

-i.bak edits your file in-place, and keeps a copy of your original file with the extension filename.bak.

's/foo.*//' is the substitution part. 'foo.*' identifies 'foo' followed by any number of characters up to the end of the line. We catch this pattern and replace it with an empty string, effectively removing it.


Here are a couple of alternatives:: using GNU grep with the perl mode enabled.

grep -Po '^.*?(?=foo|$)' file

The regex looks for the first match of foo OTW skids till the end of line. The anchoring to the beginning of line ^ prevents grep ping of multiple matches in a line and lookahead prevents the foo from being included in the match output.

Using Posix sed we place a marker \n and print only upto that incase the foo regex matched. OTW the whole line is printed.

sed -ne 's/foo/\n/;P' file

Split the line on foo so that $1 is anything prior to the first foo.

awk -F 'foo' 'NF>1 {$0=$1}1' file
  • A newline in the replacement slot of the POSIX sed must be literal, not a \n.
    – Quasímodo
    Jul 25, 2020 at 12:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.