I'm facing a problem in using the regular expression ^$ on UNIX.

When I type grep '^hello$' text on the command line, as a result it should match the "hello" word because it is the only word on a particular line in the text file. Unfortunately, it isn't doing like that.

I tried it with even when there was no word on any line except "hello" and then also it isn't working.

  • 3
    Is your file in DOS format with a CR at the end? If so you need to convert to Unix format first (dos2unix). This is common if you create files on Windows and then transfer them to Unix. Commented Jul 2, 2016 at 1:07
  • @StephenHarris How do I check that if the file is CR or not? I remember I created this "text" file using the vi text command
    – Anonymous
    Commented Jul 2, 2016 at 1:09
  • file would say something like ASCII text, with CRLF line terminators Commented Jul 2, 2016 at 1:10
  • 3
    Also cat -e text will show any CR characters as ^M Commented Jul 2, 2016 at 1:14
  • 2
    That was your problem. "hello " does not match "^hello$" because of the extra space. Commented Jul 2, 2016 at 1:21

1 Answer 1


As per the comments, there are various reasons why this may not match, but look "invisible".

One common failure mode is the file is in DOS format.

In your case, you have hidden whitespace (space or TAB characters) at the end of the line.

Commands such as tr ' ' ! < filename or cat -e filename can help expose these characters.

  • By the way, cat -e text didn't work in my case. Only tr ' ' ! < text worked and displayed the empty spaces using the ! character. Why is it like that? just asking?
    – Anonymous
    Commented Jul 2, 2016 at 1:32

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .