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. – Stephen Harris Jul 2 '16 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 Jul 2 '16 at 1:09
  • file would say something like ASCII text, with CRLF line terminators – Stephen Harris Jul 2 '16 at 1:10
  • 3
    Also cat -e text will show any CR characters as ^M – steeldriver Jul 2 '16 at 1:14
  • 2
    That was your problem. "hello " does not match "^hello$" because of the extra space. – Stephen Harris Jul 2 '16 at 1:21

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 Jul 2 '16 at 1:32

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.