m4gnet m4gnet - 1 year ago 108
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?

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

  2. Set input file

  3. Set resultant variables

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download