Reputation: 1141
I have a file that looks like this:
some random
text
00ab46f891c2emore random
text
234324fc234ba253069
and yet more text
only one line in the file contains only hex characters (234324fc234ba253069
), how do I extract that? I tried sed -ne 's/^\([a-f0-9]*\)$/\1/p' file
I used line start and line end (^
and &
) as delimiters, but I am obviously missing something...
Upvotes: 0
Views: 2835
Reputation: 174696
Grep does the job,
$ grep '^[a-f0-9]\+$' file
234324fc234ba253069
Through awk,
$ awk '/^[a-f0-9]+$/{print}' file
234324fc234ba253069
Based on the search pattern given, awk
and grep
prints the matched line.
^ # start
[a-f0-9]\+ # hex characters without capital A-F one or more times
$ # End
Upvotes: 2
Reputation: 289495
sed
can make it:
sed -n '/^[a-f0-9]*$/p' file
234324fc234ba253069
By the way, your command sed -ne 's/^\([a-f0-9]*\)$/\1/p' file
is working to me. Note, also, that it is not necessary to use \1
to print back. It is handy in many cases, but now it is too much because you want to print the whole line. Just sed -n '/pattern/p'
does the job, as I indicate above.
As there is just one match in the whole file, you may want to exit once it is found (thanks NeronLeVelu!):
sed -n '/^[a-f0-9]*$/{p;q}' file
Another approach is to let printf
decide when the line is hexadecimal:
while read line
do
printf "%f\n" "0x"$line >/dev/null 2>&1 && echo "$line"
done < file
Based on Hexadecimal To Decimal in Shell Script, printf "%f" 0xNUMBER
executes successfully if the number is indeed hexadecimal. Otherwise, it returns an error.
Hence, using printf ... >/dev/null 2>&1 && echo "$line"
does not let printf
print anything (redirects to /dev/null
) but then prints the line if it was hexadecimal.
For your given file, it returns:
$ while read line; do printf "%f\n" "0x"$line >/dev/null 2>&1 && echo "$line"; done < a
234324fc234ba253069
Upvotes: 2
Reputation: 784868
Using egrep
you can restrict your regex to select lines that only match valid hex characters i.e. [a-fA-F0-9]
:
egrep '^[a-fA-F0-9]+$' file
234324fc234ba253069
Upvotes: 1