m4gnet m4gnet - 2 months ago 6x
Bash Question

Read and Tokenize from a file in Bash

I want to read something from a file and tokenize it into several variables in Bash, but I'm not sure how.


Enter file path: foo/bar.txt
var1 = 'a'
var2 = 'b'
var3 = 'c'
var4 = 'd'

The contents of bar.txt would simply be "a,b,c,d". It would have to be a one line file. I was thinking of using grep somehow. Is there an easy way of doing this, or am I making things to complicated?

IFS=, read var1 var2 var3 var4 < bar.txt
  1. Set field separator

  2. Set input file

  3. Set resultant variables