Reputation: 313
I am trying to write a simple bash script that would grep for a string in a binary file and then using a regular expression extract all hexadecimal strings. However, I cannot seem to find a way in which I could store the output from the regex in an array which I could later on use to convert all of its elements from hexadecimal to ASCII values.
str=$(grep -ra "Html.Exploit.CVE.2015_6073" /var/lib);
hexstr=$([[ $STR =~ (?<=^|[*{};])[A-Fa-f0-9]+(?=$|[*;{}]) ]]);
converted=$(xxd -r -p <<< "$HEXSTR");
echo -e "\e[92m$converted \e[0m"
Can I do an if
statement with a while
loop in it that would create an array with the hexadecimal strings (returned from the regex) as elements?
Current code:
#!/bin/bash
str=$(grep -ra "Html.Exploit.CVE.2015_6073" /var/lib);
if [[ $str =~ (?<=^|[*{};])[A-Fa-f0-9]+(?=$|[*;{}]) ]]; then
Array+="$str"
fi
for hex in "${Array[@]}"; do
echo $hex
done
Upvotes: 0
Views: 115
Reputation: 2509
You can add values to an array like this in bash:
Array+=("$hexstr")
Then you can loop through the array like this:
for hex in "${Array[@]}"; do
#perform operation to convert hex here
converted="$(xxd -r -p <<< "$hex")"
done
To correct the if match
logic you can make a statement like this so the $hexstr
variable will get set.
if [[ $STR =~ (?<=^|[*{};])[A-Fa-f0-9]+(?=$|[*;{}]) ]]; then
hexstr="$STR"
fi
Putting this together would look like this:
if [[ $STR =~ (?<=^|[*{};])[A-Fa-f0-9]+(?=$|[*;{}]) ]]; then
Array+=("$STR")
fi
###Do work
###Use For loop etc
If you want to shorten your code even more (less code less chances to break) you can do all of the matching in the grep and add to the array like this:
Array=($( grep -ra "Html.Exploit.CVE.2015_6073" /var/lib | grep -oP "(?<=^|[*{};])[A-Fa-f0-9]+(?=$|[*;{}])"))
##Do For loop
The above will perform your grep and find only matching lines then it will get only the matching value of the regex and store each in the array.
Upvotes: 3