How can I remove rest of file from string for all files?

With GNU sed:

str="ddd"
for file in 1 2; do
    sed -i "/$str/ {s/$str.*//; q}" "$file"
done

This needs to be in a loop: otherwise the q command would abort the whole process after processing only the first file.


With Perl:

perl -i -0777 -pe 's/ddd[\s\S]*//' file

or

perl -i -0777 -pe 's/ddd.*//s' file
  • -i: modify the file in place.

  • -0777: force Perl to slurp the file as whole, not line by line.

  • -pe:

    • -p: loop Perl code.
    • -e: execute Perl code.
  • 's/ddd[\s\S]*//': replace everything (every whitespace (\s) and non-whitespace (\S) character) after ddd (including it) with an empty string.

  • 's/ddd.*//s': replace everything (.*) after ddd (including it) with an empty string. The s flag at the end makes .* also match newlines (thanks @glennjackman).

More about Perl flags can be found here.


with GNU awk, we can do:

awk 'function output(){ print >>FILENAME".out" }
     /ddd/{ sub(/ddd.*/,""); output(); nextfile }
          { output() }' file[12]

to change inplace, which it makes command even simple:

gawk -i inplace '/ddd/{ sub(/ddd.*/,""); print ; nextfile }1' file[12]