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

3 Answers 3

10

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
  • 1
    Found it interesting you answered a similar question in Unix & LInux 8 years ago: unix.stackexchange.com/a/11323/200094 Commented Oct 1, 2019 at 10:56
  • I wonder if you could just d instead of q Commented Oct 1, 2019 at 18:31
  • You're welcome to try. sed is not a go-to tool for me once things get more complicated that what I did. Commented Oct 1, 2019 at 19:08
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
    Commented Sep 30, 2019 at 16:41
  • @dessert .* stops matching at newline. Commented Sep 30, 2019 at 16:53
  • You can use..* if you add the m or s flag to the s/// command (I forget which one) Commented Sep 30, 2019 at 21:23
  • @glennjackman It's the s flag. Thanks! Commented Oct 1, 2019 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]

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .