I am trying to get a better understanding of bash commands.
ls /usr/include/ | grep \.h
It is supposed to list all the files ending in .h (C libraries) but it outputs more than expected.
thread_db .h
uchar .h
netash
If someone could also tell me how to bold the .h in the question without separating it from the rest of the name with a space, i would appriciate it.
Best Answer
In
grep
, your pattern is matching.h
(any character followed byh
) anywhere in the line, not just at the end.You basically have two problems:
Quoting/escaping issue
Regex pattern issue
Explanations:
You have escaped
.
using\.
and have not used any quotes or another\
, so the escaping would escape the shell, andgrep
would get the Regex pattern as.h
, in Regex term which means any character followed by ah
. Your target is to makegrep
treat the.
literal, so you need to quote or add another\
like:Now the second problem, in regex, the end of a line is expressed by the quantifier
$
, so as you need to match the.h
at the end of the line:So, together the correct usage would be:
Now the most important thing, Don't parse
ls
.What you are doing can be easily and efficiently done by basic shell globbing: