grep for special characters in Unix

I have a log file (application.log) which might contain the following string of normal & special characters on multiple lines:

*^%Q&$*&^@$&*!^@$*&^&^*&^& 

I want to search for the line number(s) which contains this special character string.

grep '*^%Q&$*&^@$&*!^@$*&^&^*&^&' application.log 

The above command doesn't return any results.

What would be the correct syntax to get the line numbers?

1

6 Answers

Tell grep to treat your input as fixed string using -F option.

grep -F '*^%Q&$*&^@$&*!^@$*&^&^*&^&' application.log 

Option -n is required to get the line number,

grep -Fn '*^%Q&$*&^@$&*!^@$*&^&^*&^&' application.log 
6

The one that worked for me is:

grep -e '->' 

The -e means that the next argument is the pattern, and won't be interpreted as an argument.

From:

8

A related note

To grep for carriage return, namely the \r character, or 0x0d, we can do this:

grep -F $'\r' application.log 

Alternatively, use printf, or echo, for POSIX compatibility

grep -F "$(printf '\r')" application.log 

And we can use hexdump, or less to see the result:

$ printf "a\rb" | grep -F $'\r' | hexdump -c 0000000 a \r b \n 

Regarding the use of $'\r' and other supported characters, see Bash Manual > ANSI-C Quoting:

Words of the form $'string' are treated specially. The word expands to string, with backslash-escaped characters replaced as specified by the ANSI C standard

grep -n "\*\^\%\Q\&\$\&\^\@\$\&\!\^\@\$\&\^\&\^\&\^\&" test.log 1:*^%Q&$&^@$&!^@$&^&^&^& 8:*^%Q&$&^@$&!^@$&^&^&^& 14:*^%Q&$&^@$&!^@$&^&^&^& 
0

You could try removing any alphanumeric characters and space. And then use -n will give you the line number. Try following:

grep -vn "^[a-zA-Z0-9 ]*$" application.log

1

Try vi with the -b option, this will show special end of line characters (I typically use it to see windows line endings in a txt file on a unix OS)

But if you want a scripted solution obviously vi wont work so you can try the -f or -e options with grep and pipe the result into sed or awk. From grep man page:

Matcher Selection -E, --extended-regexp Interpret PATTERN as an extended regular expression (ERE, see below). (-E is specified by POSIX.)

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

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