pogibas
pogibas

Reputation: 28339

grep from the beginning of a file (grep -f )

I use commands | grep -f - file to extract piped content from the file.
However I want to extract only if the matching string is in the beginning of the line. Usually I use grep '^string', but it doesn't work with grep -f.

grep -f '^-' file
grep: ^-: No such file or directory

How can I use grep -f - and grep '^' together?

Upvotes: 3

Views: 1923

Answers (1)

bartimar
bartimar

Reputation: 3534

grep -f is for file containing the patterns.

You cannot call grep -f '^-' because it will not take the '^-' as pattern, but as file name

If you dont want to use a file, you can use the pipe

grep -f -, where the - is signal for taking the stdin/pipe and not file.

Here is an example

echo ^a | grep -f - file.txt is the same as grep '^a' file.txt

Better usage is taking only some patterns from some file and this patterns use for your file

grep '^PAT' patterns.txt | grep -f - myfile

This will take all patterns from file patterns.txt starting with PAT and use this patterns from the next grep to search in myfile.

So you can have dictionary in the file patterns.txt and use it for searching in myfile file.

If you have some kind of dictionary (list of strings in file, separated by newlines) and want use this as patterns containing the string in the beginning of the line and you dont have the ^ in the dictionary, you can use sed

grep '^abc' dict.txt | sed 's/^/^/g' | grep -f - myfile

So, given the file dict.txt

a
abc
abcd
fbdf

will first grep take "abc" and "abcd", prefix them with ^

and call something like grep -e '^abc' -e '^abcd' myfile

Note that ^abcd is a subset of ^abc. So you would probably have a space (or another delimiter) at the end of your string

grep '^abc' dict.txt | sed 's/^/^/;s/$/\ /' | grep -f - myfile

Upvotes: 4

Related Questions