9

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

For example, input files 1 and 2, string is ddd.

Input file 1.

aaa
bbb
ccc
ddfbbd dddaaa
eee

Output file 1.

aaa
bbb
ccc
ddfbbd 

Input file 2.

ccc
aergddd
dasdvsdb

Output file 2.

ccc
aerg
11

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.

3
7

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.

4
  • Why not just s/ddd.*//?
    – dessert
    Sep 30 '19 at 16:41
  • @dessert .* stops matching at newline. Sep 30 '19 at 16:53
  • You can use..* if you add the m or s flag to the s/// command (I forget which one) Sep 30 '19 at 21:23
  • @glennjackman It's the s flag. Thanks! Oct 1 '19 at 7:33
4

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]

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.