Linux – Get ‘less’ to display filename

arch linuxgrepless

Something that seemed quite useful to me when looking for a certain var in a bunch of config files:

less * | grep some_var

So this returns the value of some_var without manually looking through all config files. Nice! But what if I didn't only want to know the value of some_var and wanted to change it? What file is it in? How do I get the less command (or grep, or another command) to display the var and what file it was found in?

I searched the man-page, but couldn't find any suitable option…

Best Answer

Why pipe less into anything? That turns it into cat. The obvious answer is

grep some_var * | less

You'll get output of the form

filename:this line contains some_var somewhere

If you pass the option -n to grep, you also get line numbers:

filename:42:this line contains some_var somewhere

Many editors have some form of file search built in, with the search results appearing in a window where you can select a line to open the corresponding file at the corresponding location. In Emacs, run M-x grep or one of its variants. In Vim, run :grep or one of its variants.

Related Question