Issue
Given a file containing a list of strings like:
File1.txt
ABC
DEF
HIJ
And a file with contents like this:
File2.txt
123 line
ABC line
HIJ line
456 line
786 line
How can remove lines from the second file that do not begin with strings in first file? Also, if possible I'd like to edit the file in place rather than create a new file.
So the resulting file would contain:
ABC line
HIJ line
I was thinking of using sed to remove the lines like this.
sed -n -e '/^ABC\|^DEF\|^HIJ/p' File2.txt
However, File1.txt contains thousands of strings to check against. It would be better to use the separate file rather than list them all in this sed command.
Solution
This might work for you (GNU sed):
sed 's#.*#/^&/p#' file1 | sed -nf - -i file2
Turn file1 into a sed script and apply it to file2.
The first sed invocation creates for each line a match string which if successful prints the line.
The second sed invocation takes the output of the first and treats it as a sed script. This invocation also sets the -n
option which ensures only the lines matched are printed and nothing else and the -i
option which edits the file in place.
Answered By - potong Answer Checked By - Cary Denson (WPSolving Admin)