I want to grep for files containing the words Dansk
, Svenska
or Norsk
on any line, with a usable returncode (as I really only like to have the info that the strings are contained, my one-liner goes a little further then this).
I have many files with lines in them like this:
Disc Title: unknown Title: 01, Length: 01:33:37.000 Chapters: 33, Cells: 31, Audio streams: 04, Subpictures: 20 Subtitle: 01, Language: ar - Arabic, Content: Undefined, Stream id: 0x20, Subtitle: 02, Language: bg - Bulgarian, Content: Undefined, Stream id: 0x21, Subtitle: 03, Language: cs - Czech, Content: Undefined, Stream id: 0x22, Subtitle: 04, Language: da - Dansk, Content: Undefined, Stream id: 0x23, Subtitle: 05, Language: de - Deutsch, Content: Undefined, Stream id: 0x24, (...)
Here is the pseudocode of what I want:
for all files in directory; if file contains "Dansk" AND "Norsk" AND "Svenska" then then echo the filename end
What is the best way to do this? Can it be done on one line?
To search multiple files with the grep command, insert the filenames you want to search, separated with a space character. The terminal prints the name of every file that contains the matching lines, and the actual lines that include the required string of characters. You can append as many filenames as needed.
Grep is a powerful utility available by default on UNIX-based systems. The name stands for Global Regular Expression Print. By using the grep command, you can customize how the tool searches for a pattern or multiple patterns in this case. You can grep multiple strings in different files and directories.
For BSD or GNU grep you can use -B num to set how many lines before the match and -A num for the number of lines after the match. If you want the same number of lines before and after you can use -C num . This will show 3 lines before and 3 lines after.
You can use:
grep -l Dansk * | xargs grep -l Norsk | xargs grep -l Svenska
If you want also to find in hidden files:
grep -l Dansk .* | xargs grep -l Norsk | xargs grep -l Svenska
Yet another way using just bash and grep:
For a single file 'test.txt':
grep -q Dansk test.txt && grep -q Norsk test.txt && grep -l Svenska test.txt
Will print test.txt
iff the file contains all three (in any combination). The first two greps don't print anything (-q
) and the last only prints the file if the other two have passed.
If you want to do it for every file in the directory:
for f in *; do grep -q Dansk $f && grep -q Norsk $f && grep -l Svenska $f; done
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With