1

Hello i'm trying to find all occurrences of a word in a subfolder. While that seems to be easy i want that for each occurrence we will display the path and the name of the file followed by ' -> Line: ', followed by the number of the line containing this occurrence.

For example : example/example/file.png -> Line: 25

I tried to do : grep -rnl 'word' subfolder/ | sed 's/$/ -> Line : /' But i can't find a way to print the line at the end Heres an example of what i get using this command : ( example/example/file.png -> Line: )

Thanks in advance for your help

3
  • Have a look at awk instead of sed
    – Chai Ang
    Feb 22 at 6:07
  • Maybe grep -rn 'word' subfolder | awk -F":" '{print $1 " -> " "Line: " $2}' or using find find -type f -exec grep -n 'word' {} + | awk -F":" '{print $1 " -> " "Line: " $2}' Feb 22 at 6:47
  • Thanks a lot grep -rn 'word' subfolder | awk -F":" '{print $1 " -> " "Line: " $2}' worked for me
    – Mnako8
    Feb 26 at 22:24

1 Answer 1

1

In grep -rnl 'word' subfolder/, -n conflicts with -l. You have to decide whether you want only the file names (-l) or all the matches to be printed along with the line number (-n).

So assuming you meant the latter, grep -rn pattern folder/ would print something like:

folder/file:4:line with pattern
folder/file:with:colon:12:other pattern line
folder/subfolder:with:colon/file
with
newline:12:pattern again

And it should be obvious that there's no way to extract the line number from that.

It can only be done if you can guarantee file paths won't contain : nor newline characters. Maybe with something like:

grep -rn pattern folder/ |
  LC_ALL=C sed 's/^\([^:]*\):\([^:]*\)\(.*\)/\1\3 -> Line: \2/'

To do it reliably regardless of what character or non-character the file paths may contain¹, you'd need:

find folder/ -type f -exec awk '
  /pattern/ {
    print FILENAME":"$0" -> Line: "FNR
  }' {} +

Which also removes the need for the non-standard and unportable -r option of grep.


¹ Though possibly less reliably if the directory hierarchy is so deep that file path lengths exceed PATH_MAX.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.