0

I have file with hex symbols like below

cat demo 
\x22count\x22
\x22count\x22
\x22count\x22

I need conversion like:

echo $(cat demo)
"count" "count" "count"

How to get unicode symbols in pipeline with newline symbol? Something like:

cat demo | ???

"count" 
"count" 
"count"

2 Answers 2

1

You can use printf's %b conversion specification. This will print the output you want:

printf '%b\n' "$(<demo)"

Note: %b causes printf to expand other backslash escape sequences as well (e.g., \n, \t etc.)

Sign up to request clarification or add additional context in comments.

4 Comments

thanks, it works! Could you please advise, how to use it with pipe? Something like cat /tmp/ssv_count | xargs -I{} printf '%b\n' {} . My command returns x22countx22 three times
@gayavat xargs is error-prone and rarely useful in a bash script. You shouldn't use it unless you have to. But if you really insist, this should work for GNU xargs : cat /tmp/ssv_count | xargs -d '\n' -I{} printf '%b\n' {} . (-d option is not specified in the POSIX standard, but is implemented by GNU systems).
Excellent! thanks a lot! Is it any alternative of xargs? if i need use printf in the middle of pipeline? I.e something like cat demo | xargs -d '\n' -I{} printf '%b\n' {} | grep count > result
@gayavat printf '%b\n' "$(<demo)" | grep count > result if you want to grep after the %b conversion, or, printf '%b\n' "$(grep count demo)" > result if you want to grep before the %b conversion.
1

You could use printf to convert the hexadecimal data. Depending on the size of your input, you could read the lines into an array then use IFS to delimit the output:

join() {
    local IFS="$1"
    shift
    echo "$*"
}
arr=( $(while read -r line; do printf "$line "; done < demo) )

join $' ' "${arr[@]}"
"count" "count" "count"

join $'\n' "${arr[@]}"
"count"
"count"
"count"

1 Comment

Yes, printf can be used for this purpose, but the way it is used in this answer is incorrect. printf's format string shouldn't come from user input (unless the input is supposed to be a format string): It won't produce correct output if the input contains format specifications (eg, %s, %d, etc.).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.