Reputation: 43
I have a TSV table and I'm trying to use bash to extract values from a specific row based on the user's input, and then assign those values to variables for use later.
Example table (columns are tab-delimited):
NAME FOOD TIME
Eric pasta 8pm
Sally bread 11am
Jeff ribeye steak with fries 10pm
My goal:
echo Enter your name
read name
echo Hello, $name
(Select the row that matches the $name value and assign FOOD and TIME to $food and $time respectively)
echo You'll be having $food at $time
I did some reading and perhaps awk might be able to accomplish this, but I'm completely lost. How should I go about doing this?
Upvotes: 2
Views: 1288
Reputation: 247042
A bash solution:
read -p 'Enter your name: ' yourName
echo "Hello, $yourName"
found=0
while IFS=$'\t' read -r name food time; do
if [[ "$name" == "$yourName" ]]; then
found=1
break
fi
done < input.tsv
if [[ $found -eq 1 ]]; then
echo "You'll be having $food at $time"
else
echo "Name $yourName not found"
fi
Upvotes: 2
Reputation: 35146
Any command that can pull the 2x desired values out and display then on one line should work; from here you can read these 2x values into your variables with the read
command.
Sample data:
$ cat mytsv # tab-delimited columns
NAME FOOD TIME
Eric pasta 8pm
Sally bread 11am
Jeff ribeye steak with fries 10pm
We'll start by using awk
to pull out the 2 fields of interest, making sure to use an output field separator that does not exist in the actual data (eg, OFS=":"
):
$ name='Jeff'
$ awk -F'\t' -v ptn="${name}" 'BEGIN {OFS=":"} $1==ptn {print $2,$3}' mytsv
ribeye steak with fries:10pm
We can now combine IFS
(set to :
) and read
to pull these values into our 2x variables, eg:
$ IFS=":" read -r food time < <(awk -F'\t' -v ptn="${name}" 'BEGIN {OFS=":"} $1==ptn {print $2,$3}' mytsv)
$ echo "${food}"
ribeye steak with fries
$ echo "${time}"
10pm
$ echo "You'll be having ${food} at ${time}"
You'll be having ribeye steak with fries at 10pm
Upvotes: 3
Reputation: 12887
Using GNU awk:
awk -F "\t" -v nam="$name" '$1==nam { printf "You will be having %s at %s\n",$2,$3 }' file
Set the field delimiter to tab and pass variable nam into awk using the variable name. When the first tab delimited field is equal to nam, print the 2nd and 3rd delimited fields in the format required
Upvotes: 3