How to escape "." with sed or grep?
I have file
with
denm.xyz
denm.abc
denm.def
denm_xyz
denm_abc
denm_def
I want to extract the ones with .
in it.
I tried
grep "denm\.*" file
grep 'denm\.*' file
sed "/denm\.*/p" file
sed '/denm\.*/p' file
These things are matching everything in the file
However using awk
awk '/denm\./' file
worked!!
How do I do same using grep
or sed
You were close, you just need to remove *
which means zero or more match of the preceding token, .
in this case. As a result the demn_
is also being showed in the result as it matched the condition of zero .
.
So you can do:
grep 'denm\.' file.txt
Similarly in sed
:
sed -n '/denm\./p' file.txt
Note that you have missed the -n
option of sed
, without it sed
will print all the lines too.
There are also so many level of precision can be added to get exactly what you want in complex cases but take it as a start.
Example:
% grep 'denm\.' file.txt
denm.xyz
denm.abc
denm.def
% sed -n '/denm\./p' file.txt
denm.xyz
denm.abc
denm.def
\.*
means "any number of occurrences of the character .
", including zero. Since your underscored filenames start with denm
followed by zero occurrences of the character .
, they are matched. grep "denm\." file
will work.
If all you need are the lines that have a .
in them, used grep with fixed strings instead of regular expressions:
grep -F . file
From man grep
:
-F, --fixed-strings
Interpret PATTERN as a list of fixed strings, separated by
newlines, any of which is to be matched. (-F is specified by
POSIX.)
With fixed strings, all regular expression special characters lose their meaning.
sed
does not have a corresponding option.
I tend to use brackets instead of backslashes for escaping:
egrep "denm[.].*" file
sed -r 's/denm[.]/.../'
This saves me the effort of thinking if and how I should escape the backslashes. (The final .*
is redundant here.)