I am using Ubuntu 16.04.
I want to search for a certain word, but I also want the whole file that contains the word to be outputted on the terminal so that I can see where in the file the word is located. However, when I use grep
, it will only show the particular sentence that contains the word, not the whole file.
What command can I use to search for a word but also show the whole file along with the place where the word is located?
With
grep
you can use:or in a simplified form:
Technically this would work too:
or even :
grep -E 'pattern|' file
. It says lines withpattern
or no pattern at all. so everything will match.I have
grep
aliased togrep --color=always
, so if you don't you have to pass the color option yourself.With
less
:So the file would pop-up in less, the desired term would be highlighted and you can use n and shift+n to jump around between matches.
Edit: I misinterpreted the question in my original answer.... I have edited it to produce the desired result... I was only showing the file name in the output. I edited this answer to use that output to show the entire file by using less (as Ravexina's answer suggests)
...in addition, this will only return the files (in
less
) that have been matched by grep when searching through a directory(s).....and I added
-I
to ignore binary files, they may make theless
interaction messy. Remove it if you need to search binary files or files that grep may "think" are binary.Use the "with-filename" flag with grep to show the file. (the flag is
-H
)I am assuming you are combing through a directory and each of the files in them. If searching outside of current directory, use the
*
to prevent "is a directory" error with no results.grep -HI pattern /directory/* | less -p pattern $(awk -F ":" '{print $1}')
or
grep --with-filename -I pattern /directory/* | less -p pattern $(awk -F ":" '{print $1}')
or if drilling down into sub-directories...
grep -rHI pattern /directory/* | less -p pattern $(awk -F ":" '{print $1}')
I don't like entering the pattern twice, it could use improvement
If you want to see where in the file your searched text is use C flag. For example:
will show the line containing the text and five lines before and five lines after the intended search.
To complement the other answers: you can add '-n' to the options to see the line numbers on the left:
will show you lines containing "something", with 3 lines of "Context" (ie, 3 lines before and after the one(s) matching "something"), and each shown lines will have its line number appended at the beginning.