2

example) When I search the exec in proc.c file,

$ ack allocproc proc.c

allocproc(void)
p = allocproc();
if((np = allocproc()) == 0){
// Return to "caller", actually trapret (see allocproc).

but when I search in the whole directory,

$ ack allocproc

---- blah blah blah ----

proc.c
36:allocproc(void)
84:  p = allocproc();
139:  if((np = allocproc()) == 0){
357:  // Return to "caller", actually trapret (see allocproc).

... I want to show lines when I search a string in the single file...

Andy Lester
  • 91,102
  • 13
  • 100
  • 152
MangoTatsy
  • 173
  • 1
  • 13

3 Answers3

2

Maybe add a line in .bashrc alias ackl='ack -H'

and use ackl command as default... will solve this temporarily.

MangoTatsy
  • 173
  • 1
  • 13
1

The -H flag in ack will force ack to put a file header and line number on every file. This behavior is copied directly from GNU grep.

You point out the option of creating a shell alias. Another option is to put the -H in an ackrc file. ack supports three different places to find an ackrc. There's a system-wide one in /etc/ackrc, there's one that's personal to you in your ~/.ackrc file, and you can also have a project-specific file, typically in the root of a project.

For more about ackrc files, look at the ack manual (ack --man is one way to see it) and look for the section "THE .ackrc FILE" and "ACKRC LOCATION SEMANTICS".

The one downside to putting -H in your .ackrc is that it will always be in force no matter how you call ack, so if, for example, you're piping output from one process through ack, ack will still show the heading and line numbers.

One other way to deal with this: Just add the -H option when you need it.

Andy Lester
  • 91,102
  • 13
  • 100
  • 152
  • 1
    in that case maybe i can use **ack** because **alias ackl=‘ack -H’** means just add one shortcut for **ack**. – MangoTatsy Oct 03 '18 at 21:55
0

I've discovered that, in both grep and ack, if they behave differently with one file than they do with multiple files, you can force the multiple-file behavior by including /dev/null as a second file to search through.

Of course, using the -H switch is much cleaner (and has the advantage of being listed in the documentation, so that curious maintainers can see the exact purpose behind its use), but if you're in a pinch and don't have the documentation available (or if you're using some other program that behaves differently with one vs. with multiple files), then using /dev/null will probably work.

I don't recommend using this /dev/null technique in commands called in scripts -- in such cases, the -H switch is the preferred method, unless for some reason -H is literally unavailable to you.

J-L
  • 1,786
  • 10
  • 13