How can I remove rest of file from string for all files?
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
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) afterddd
(including it) with an empty string.'s/ddd.*//s'
: replace everything (.*
) afterddd
(including it) with an empty string. Thes
flag at the end makes.*
also match newlines (thanks @glennjackman).
More about Perl flags can be found here.