3

I have a file with text inside of it like so:

471_068 0
AALIAN  1
ASHLEY-U    95
CATRIONA_W  97
STESSY K    08

This data is related to an items "Name" and it's "Color ID"
I need to split the Name from the ID and house them in separate variables.


As a note, the ID when using a digit under 10 can both have a leading 0 or not, so I need to parse those as they appear (a 04 will need to stay 04 and a 1 will need to remain 1 not 4 or 01)

The Names can have an underscore(_), hyphen(-) or space ( ) in them which would need to be preserved as well.

Here is what I have for reading the file, which reads the file line by line in the loop which is great but I can't figure out how to get the variables I want separated correctly.

while read fLine
do
  PRDT=$(echo $fLine | tr '\t' '\n')
  echo First Var is ${PRDT[0]} - Second Var is ${PRDT[1]}
done < Products
Fate Averie
  • 359
  • 4
  • 7
  • 17
  • Is the Name and Color separated by tab, or just multiple spaces? Have you considered using awk? – SiKing Feb 28 '17 at 18:11
  • I guess I forgot to mention that, yes the two variables I want are separated by a TAB, they come from a TSV file. – Fate Averie Feb 28 '17 at 18:42

1 Answers1

6

read can do this itself. See BashFAQ #1.

while IFS=$'\t' read -r key value; do
  echo "First Var is $key - Remaining Line Contents Are $value"
done

Note that if you want to discard any content after the second column (rather than appending that content to the value), this would instead be:

while IFS=$'\t' read -r key value _; do
  echo "First Var is $key - Second Var is $value"
done

If you want to store the IDs in such a way as to be able to look them up by name, an associative array (added in bash 4.0) is the right tool:

declare -A color_ids=( )
while IFS=$'\t' read -r key value; do
  color_ids[$key]=$value
done

for name in "${!color_ids[@]}"; do
  value=${color_ids[$name]}
  echo "Stored name $name with value $value"
done
Charles Duffy
  • 280,126
  • 43
  • 390
  • 441
  • the first part works exactly the way I need it, I should have read up on the ```read``` man page a little more before asking this >. – Fate Averie Feb 28 '17 at 18:31