dev_paul
dev_paul

Reputation: 3

Retrieve string between characters and assign on new variable using awk in bash

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.

Upvotes: 0

Views: 156

Answers (2)

David C. Rankin
David C. Rankin

Reputation: 84579

In addition to using awk, you can use the native parameter expansion/substring extraction provided by bash. Below # indicates a trim from the left, while % is used to trim from the right. (note: a single # or % indicates removal up to the first occurrence, while ## or %% indicates removal of all occurrences):

#!/bin/bash

[ -r "$1" ] || {    ## validate input is readable
    printf "error: insufficient input. usage: %s filename\n" "${0##*/}"
    exit 1
}

## read each line and separate label and value
while read -r line || [ -n "$line" ]; do
    label=${line#[}     # trim initial [ from left
    label=${label%%]*}  # trim through ] from right
    value=${line##*] }  # trim from left through '[ '
    printf " %-8s -> '%s'\n" "$label" "$value"
done <"$1"

exit 0

Input

$ cat dat/labels.txt
[apple] This is a fruit.
[ball] This is a sport's equipment.
[cat] This is an animal.

Output

$ bash readlabel.sh dat/labels.txt
 apple    -> 'This is a fruit.'
 ball     -> 'This is a sport's equipment.'
 cat      -> 'This is an animal.'

Upvotes: 0

Cyrus
Cyrus

Reputation: 88756

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

Upvotes: 0

Related Questions