Alin Tomescu
Alin Tomescu

Reputation: 393

How to grep for a pattern in multiple files while excluding commented lines

I have a bunch of LaTeX files that I want to search using grep pattern *.tex -n --color=always. It's important that I see:

  1. The file's name that matched
  2. The line number of the match
  3. The full line, with the matched pattern highlighted

Furthermore, sometimes the pattern needs to be a full word match, so the command becomes grep pattern *.tex -n -w --color=always

I would like to modify this command to exclude commented lines in my *.tex files, which start with the % character. I am not interested in matches in comments.

Is this possible?

Upvotes: 0

Views: 127

Answers (2)

James Brown
James Brown

Reputation: 37404

Would this do? First some test stuff:

$ cat file
yes
no % yes commented out
yes % yes before comment
no
noyes
furthermore yes
furthermore yes% yes
furthermore no% yes

The grep:

$ grep -Hn "^[^%]*\(^\| \)yes\( \|$\|%\)" file
file:1:yes
file:3:yes % yes before comment
file:6:furthermore yes
file:7:furthermore yes% yes

Edit: For partial matches:

$ grep -Hn "^[^%]*yes" file 

and to highlight only the search word you need to grep for it again:

$ grep -Hn "^[^%]*yes" file | grep yes
file:1:yes
file:3:yes % yes before comment
file:5:noyes
file:6:furthermore yes
file:7:furthermore yes% yes

Upvotes: 0

Pietro Martinelli
Pietro Martinelli

Reputation: 1906

May be you can try the following command:

grep -n -v --color=always '^%' *.tex | grep content

EXPLANATION

  • The first grep invocation excludes (-v) line starting with % (regex ^% matches % at the start of the line (^))
  • The output of the first grep invocation is passed as input to the second grep invocation
  • The second grep invocations includes only rows matching with your filter pattern (you can add -w option if you need it).

I hope this can help you!

Upvotes: 1

Related Questions