grep for special characters in Unix

后端 未结 6 501
你的背包
你的背包 2020-12-02 06:02

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

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


        
相关标签:
6条回答
  • 2020-12-02 06:41

    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.)
    
    0 讨论(0)
  • 2020-12-02 06:51

    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

    0 讨论(0)
  • 2020-12-02 06:52
    grep -n "\*\^\%\Q\&\$\&\^\@\$\&\!\^\@\$\&\^\&\^\&\^\&" test.log
    1:*^%Q&$&^@$&!^@$&^&^&^&
    8:*^%Q&$&^@$&!^@$&^&^&^&
    14:*^%Q&$&^@$&!^@$&^&^&^&
    
    0 讨论(0)
  • 2020-12-02 06:53

    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: http://www.linuxquestions.org/questions/programming-9/how-to-grep-for-string-769460/

    0 讨论(0)
  • 2020-12-02 06:58

    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

    0 讨论(0)
  • 2020-12-02 07:04

    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
    
    0 讨论(0)
提交回复
热议问题