I have a file of property: value;
pairs (it's CSS). I want to go through this file and regex extract certain values to shell variables, while replacing the text in the file with a marker.
Eg for FILE1:
position: float;
background: url("data:image/loremipsum");
height: auto;
background: url("data:image/loremipsum2");
And let's say I want to extract and save the image urls to an array:
FILE1=path/to/file1
URL[0]=$(echo "$FILE1" | grep "data:image" | awk ???)
# Expected: "data:image/loremipsum"
URL[1]=$(echo "$FILE1" | grep "data:image" | awk ???)
# Expected: "data:image/loremipsum2"
And then, from where I extracted the text, that text is replaced with "MARKER0", "MARKER1", and so on.
I'm assuming that the solution for this would involve awk but I typed man awk
and my head nearly came off. Assuming that I know how to write the regex for this, where do I start?
Do I need awk? Do I need a loop to iterate through each of the image values?
Could you please try following.
arr=($(awk '/background/ && match($0,/\".*\"/){print substr($0,RSTART+1,RLENGTH-2)}' Input_file))
OR to use a variable's value for awk as an input then try following.
arr=($(echo "$VAR" | awk '/background/ && match($0,/\".*\"/){print substr($0,RSTART+1,RLENGTH-2)}'))
To print the array's values try following then.
for i in "${arr[@]}"
do
echo "$i"
done
Or to print in proper knowing element's index value too with print of array's value try following.
count=0
for i in "${arr[@]}"
do
echo "arr["$count"]=$i"
count=$((count + 1))
done
EDIT: Since OP is saying there could be space in between values. So possible solution for this could be printing values from awk
command with a new character between the values(which will work as a field separator for BASH array's iterations), I have taken %
so when you run awk command it will give follows.(using test values in output shown here)
awk '/background/ && match($0,/\".*\"/){val=val?val "%" substr($0,RSTART+1,RLENGTH-2):substr($0,RSTART+1,RLENGTH-2)} END{print val}' Input_file
singh:test/ bla_bla_bla%singh:bla1/bla2
Run following command to create array named arr
.
arr=($(awk '/background/ && match($0,/\".*\"/){val=val?val "%" substr($0,RSTART+1,RLENGTH-2):substr($0,RSTART+1,RLENGTH-2)} END{print val}' Input_file))
Now if we set IFS='%'
and run following command.
echo "${arr[0]}"
singh:test/ bla_bla_bla
echo "${arr[1]}"
singh:bla1/bla2
Since it has taken new seprator as %
so it will NOT break values for which have space in them.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments