How to grep a line with a backslash at the end of the line?

I'm trying to grep a line with a backslash at the end of the line like:

abc\ def ghij ... 

I hope it can grep the line "abc\". I tried the command below but they didn't work.

grep -EHn "\\$" test_file grep -PHn "\\$" test_file 

How should I solve this problem? I just don't know the logic of escape character in grep. The expression did work in vim.

3 Answers

grep '\\$' test_file 

works fine for me on Solaris 9 and Ubuntu 12.04.

Single quotes and double quotes differ in which characters are taken literally or used as escape/special characters.

1

I somehow overcame the problem by using below:

grep -Hn "\\\\$" 

But I'm not sure why four back slash would work here. It just worked.

1

From "man grep" command:

-F, --fixed-strings Interpret PATTERNS as fixed strings, not regular expressions.

-o, --only-matching Print only the matched (non-empty) parts of a matching line, with each such part on a separate output line.

Also, you have to surround your target with a single quote mark to capcher the exact character:

input:

$echo " this is a backslash -- > '\' " | grep -oF '\' 

output:

\ 

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like