Mohammad Yusuf Ghazi Mohammad Yusuf Ghazi - 11 months ago 33
Python Question

Extracting lines by pattern matching from multiple files and writing them to another file in linux

I have 20 files. I want to extract lines by matching a pattern from those 20 files and write it to new file.

I also want to delete those lines from the original files.

Can someone explain how to do it in linux using bash/python?

Check my attempt in the answers.


Using sed:

sed -i -e "/$pattern/w $newfile" -e "/$pattern/d" $files

Sed's w command writes match to some other file. d deletes it.


$ pattern='<script src="{%'
$ files=/home/username/folder/*
$ newfile=/home/username/file.txt
$ sed -i -e "/$pattern/w $newfile" -e "/$pattern/d" $files