19

I'm using ack to search for a string. When I run it without a file argument, I get line numbers:

$> ack function
themes/README.txt
7:Drupal's sub-theme functionality to ensure easy maintenance and upgrades.

sites/default/default.services.yml
48:    # - The dump() function can be used in Twig templates to output information

...

But when I try to specify a file, I don't get line numbers.

$> ack function themes/README.txt
Drupal's sub-theme functionality to ensure easy maintenance and upgrades.

I've done some googling for a switch, but found no results. How do I get ack to show me line numbers on results from a single file?

user394
  • 14,404
  • 21
  • 67
  • 93

3 Answers3

22

When you don't provide any file, ack will search for all files in current directory and subdirectories. If a file contains matching pattern, ack print that filename, the line number and the line which matched pattern.

This behaviour does not apply for one file (See ack documentation, search for -H option).

Since when ack doesn't have -n option line grep, which will print line matched with its relative line number, you have two choices to work around this issue.

Forcing ack print filename with -H:

ack -H pattern file

or passing /dev/null as the second file:

ack pattern file /dev/null
cuonglm
  • 153,898
9

You can try with option --with-filename:

ack --with-filename 'function' themes/README.txt

This issue is raised as bug and issue has been moved here.

taliezin
  • 9,275
5

There should be an option for this. But if there isn't, you can trick ack into thinking there are two files to search through, by passing an extra /dev/null on the command line:

ack function themes/README.txt /dev/null

On a side note, the same trick can be used to make grep(1) show you a filename even when you're searching a single file:

grep function themes/README.txt /dev/null
lcd047
  • 7,238