deaddroid deaddroid - 5 months ago 21
Bash Question

Extract text with any command in linux shell

How do I extract the text from the following text and store it to the variables:

05:21-09:32, 14:21-19:30


Here, I want to store 05 in one variable, 21 in another, 09 in another and so on. All the value must me stored in array or in separate varibles.

I have tried:

k="05:21-09:32, 14:21-19:30"

part1=($k | awk -F"-" '{print $1}' | awk -F":" '{print $1}')
part2=($k | awk -F"-" '{print $2}' | awk -F":" '{print $1}')
part3=($k | awk -F"," '{print $2}' | awk -F":" '{print $1}')
part4=($k | awk -F"-" '{print $3}' | awk -F":" '{print $1}')


I need a more clear solution or short solution.

Answer

Your code has a number of problems.

  • You can't pipe the value of k to standard output with just $k -- you want something like printf '%s\n' "$k" or perhaps the less portable echo "$k"
  • Notice also the quoting in the expression above; without it, the shell will perform wildcard expansion and whitespace tokenization on the value
  • Spawning two Awk processes for a simple string substitution is excessive
  • Spawning a separate pipeline for each value you want to extract is inefficient; if at all possible, extract everything in one go.

Something like IFS=':-, '; set -- $k will assign the parts to $1, $2, $3, and $4 in one go.

Comments