【问题标题】:Grep for variable hex value用于变量十六进制值的 Grep
【发布时间】:2021-02-16 03:27:55
【问题描述】:

我正在尝试计算一个十六进制值在文件中出现的次数。十六进制值设置在变量中。

使用文字字符串“x01”返回正确的计数:

grep -o $'\x01' ${fileName} | wc -l

如何使用变量代替 x01

【问题讨论】:

    标签: bash grep


    【解决方案1】:

    借用Conversion hex string into ascii in bash command line

    # single quote character in hex
    $ a='\x27'
    
    $ echo "a'b'c" | grep -o $(echo "$a" | xxd -r -p)
    '
    '
    
    $ echo "a'b'c" | grep -o $(echo "$a" | xxd -r -p) | wc -l
    2
    
    # you can also use just the number, \x prefix is optional
    $ echo "a'b'c" | grep -o $(echo '27' | xxd -r -p) | wc -l
    2
    
    # if PCRE is available
    $ echo "a'b'c" | grep -oP "$a" | wc -l
    2
    
    # with ripgrep (https://github.com/BurntSushi/ripgrep)
    $ echo "a'b'c" | rg -oc "$a"
    2
    

    【讨论】:

    • 感谢您的回答,我认为这对我有用: grep -Fo $(echo "${delim1}" | xxd -r -p) ${filename} | wc -l
    • @Fiddlestiques 这是因为 grep 在搜索之前删除换行符并在打印时将其添加回来
    猜你喜欢
    • 2014-07-31
    • 2018-12-06
    • 2013-07-04
    • 1970-01-01
    • 2018-07-26
    • 2019-03-12
    • 2014-03-31
    • 1970-01-01
    • 2018-01-05
    相关资源
    最近更新 更多