6

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

13

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
  • This works!!. How about sed. The same is not working with it – Ramana Reddy Dec 11 '15 at 10:19
  • @RamanaReddy You have missed the -n option of sed ..check my edits.. – heemayl Dec 11 '15 at 10:23
  • you may also use char class [] for escaping, like [.] – Avinash Raj Dec 12 '15 at 11:23
7

\.* 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.

  • Well this works. How about sed – Ramana Reddy Dec 11 '15 at 10:19
3

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.

1

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.)

  • note that some may misunderstand this like [+.] used for escaping + and . but what it does it matches only one character whether it may be + or . – Avinash Raj Dec 12 '15 at 11:25

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.