3

I am trying to count the number of times a hex value appears in a file. The hex value is set in a variable.

Using the literal string "x01" returns the correct count:

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

How can I use a variable in place of x01 ?

1 Answer 1

1

Borrowing from 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 
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks using your answer, I think this will work for me: grep -Fo $(echo "${delim1}" | xxd -r -p) ${filename} | wc -l
@Fiddlestiques that's because grep removes the newline before searching and adds it back when printing

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.