4

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...

2 Answers 2

7

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.

1
  • Thanks, I guess I couldn't think the other way round, I'm always using grep in some other situation as a kind of 'helper command', not realizing I could use it on its own just as well. Extra points for the -n option, quite handy.
    – kasimir
    Jun 17, 2013 at 18:04
6

less isn't really meant for doing what you're trying to do; it's for displaying long text files in a paginated format.

grep allows for a file or list of files to be passed as a command line argument, so you can simply do

grep -H some_var *

which will give you output that looks like this because the -H option prefixes the name to the result:

filename: some_var blah blah

If you still want to pipe it into less so that you can scroll through it, you're able to do that.

grep -H some_var * | less

Another recommendation for grepping through numerous files is ack or ack-grep as it's known on Debian systems. It's designed for searching source trees fairly quickly by ignoring binary files and also requires less keystrokes to do similar searches.

3
  • Equally right, good point about the purpose of less being to display long text files.
    – kasimir
    Jun 17, 2013 at 18:06
  • note, if glob pattern (* in this case) matches only 1 file, grep will not display a file name, so you have to force it: grep -H Jun 18, 2013 at 9:07
  • @sendmoreinfo: Thanks, good point. Added that in.
    – j883376
    Jun 18, 2013 at 10:50

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .