Reputation: 12807
I have a binary file containing ascii
values and \000
: its name is input and this is its hexdump (xxd -c 1
):
0000000: 68 h
0000001: 65 e
0000002: 6c l
0000003: 6c l
0000004: 6f o
0000005: 20
0000006: 00 .
0000007: 20
0000008: 77 w
0000009: 6f o
000000a: 72 r
000000b: 6c l
000000c: 64 d
I'm trying to create a script to parse this file, and yield the string up to the null byte.
this is my attempt so far:
buf=""
for x in $(xxd -p -c 1 input); do
echo "x = $x"
if [ ${x} == 00 ]; then
echo "break"
break;
else
y=$(echo $x | xxd -r)
echo "y = $y"
echo "buf = $buf"
buf="$buf$y"
fi
done
echo $buf
The output is:
x = 68
y =
buf =
x = 65
y =
buf =
x = 6c
y =
buf =
x = 6c
y =
buf =
x = 6f
y =
buf =
x = 20
y =
buf =
x = 00
break
so at least I'm breaking the loop at the right time, but I don't understand why the assignment is not happening right
Upvotes: 1
Views: 2242
Reputation: 12807
Ok, figured it out.
xxd -r
expects 0x
as a prefix to identify the hexadecimal number. This solved it for me:
y=$(echo "0x$x" | xxd -r)
Though, I must admit this is weird, because I thought echo "a" | xxd -p | xxd -r
should result in the original letter
Upvotes: 2
Reputation: 1527
There's a better solution! head
supports NUL as a line delimiter. Try
head -zn1 input
In case you need other fields, try
head -zn7 input | tail -zn1
Upvotes: 0