I’m new to bash scripting, I’m learning how commands work, I stumble in this problem,
I have a file /home/fedora/file.txt
Inside of the file is like this:
[apple] This is a fruit. [ball] This is a sport's equipment. [cat] This is an animal.
What I wanted is to retrieve words between “[” and “]”.
What I tried so far is :
while IFS='' read -r line || [[ -n "$line" ]]; do echo $line | awk -F"[" '{print$2}' | awk -F"]" '{print$1}' done < /home/fedora/file.txt
I can print the words between “[” and “]”.
Then I wanted to put the echoed word into a variable but i don’t know how to.
Any help I will appreciate.
Advertisement
Answer
Try this:
variable="$(echo $line | awk -F"[" '{print$2}' | awk -F"]" '{print$1}')"
or
variable="$(awk -F'[[]]' '{print $2}' <<< "$line")"
or complete
while IFS='[]' read -r foo fruit rest; do echo $fruit; done < file
or with an array:
while IFS='[]' read -ra var; do echo "${var[1]}"; done < file