I am trying to use a shell script (well a "one liner") to find any common lines between around 50 files. Edit: Note I am looking for a line (lines) that appears in all the files
So far i've tried grep grep -v -x -f file1.sp *
which just matches that files contents across ALL the other files.
I've also tried grep -v -x -f file1.sp file2.sp | grep -v -x -f - file3.sp | grep -v -x -f - file4.sp | grep -v -x -f - file5.sp
etc... but I believe that searches using the files to be searched as STD in not the pattern to match on.
Does anyone know how to do this with grep or another tool?
I don't mind if it takes a while to run, I've got to add a few lines of code to around 500 files and wanted to find a common line in each of them for it to insert 'after' (they were originally just c&p from one file so hopefully there are some common lines!)
Thanks for your time,
Combining this two answers (ans1 and ans2) I think you can get the result you are needing without sorting the files:
Simply save it, give it execution rights (
chmod +x compareFiles.sh
) and run it. It will take all the files present in the current working directory and will make an all-vs-all comparison leaving in the "matching_lines" file the result.Things to be improved:
Hope this helps.
Best,
Alan Karpovsky
old, bash answer (O(n); opens
2 * n
files)From @mjgpy3 answer, you just have to make a for loop and use
comm
, like this:Save in a
comm.sh
, make it executable, and callassuming all your filenames end with
.sp
.Updated answer, python, opens only each file once
Looking at the other answers, I wanted to give one that opens once each file without using any temporary file, and supports duplicated lines. Additionally, let's process the files in parallel.
Here you go (in python3):
Save it into a
find_common_lines.py
, and callMore usage info with the
--help
option.When I first read this I thought you were trying to find 'any common lines'. I took this as meaning "find duplicate lines". If this is the case, the following should suffice:
Upon re-reading your question, it seems that you are actually trying to find lines that 'appear in all the files'. If this is the case, you will need to know the number of files in your directory:
If this returns the number 50, you can then use
awk
like this:You can consolidate this process and write a one-liner like this:
See this answer. I originally though a
diff
sounded like what you were asking for, but this answer seems much more appropriate.