Operating System - HP-UX
1832785 Members
3555 Online
110045 Solutions
New Discussion

read file data into a variable

 
SOLVED
Go to solution
Kevin Medlin
Occasional Contributor

read file data into a variable

Hi everyone,

I have a script that needs to read the date from a file and put it into a variable. The file only has one row and one column of data. For example,

> more date_file.dat
20030331

I'm trying to read date_file.dat and put it into var1. I only need to do this once so I don't need a loop or anything.

Thanks for the help.
8 REPLIES 8
Pete Randall
Outstanding Contributor

Re: read file data into a variable

export var1=`cat date_file.dat`


Pete

Pete
Jose Mosquera
Honored Contributor

Re: read file data into a variable

Hi,

If date_file.dat just have the date info:
VAR1=`cat date_file.dat`

Rgds.
John Poff
Honored Contributor

Re: read file data into a variable

Hi,

You can also do it this way:

VAR1=$(

JP


curt larson_1
Honored Contributor

Re: read file data into a variable

var=$(
Sridhar Bhaskarla
Honored Contributor
Solution

Re: read file data into a variable

Hi

var1=$(cat data_file.dat)

However, if data_file.dat has multiple lines, then your commands have to deal with them.

-Sri
You may be disappointed if you fail, but you are doomed if you don't try
Paul Sperry
Honored Contributor

Re: read file data into a variable

#!/usr/bin/ksh
for var1 in `date_file.dat`
do
whatever comman you want to do with var1
done
James R. Ferguson
Acclaimed Contributor

Re: read file data into a variable

Hi Kevin:

Do this:

VAR=`< data_file.dat`

...or:

VAR=$(< data_file.dat)

Regards!

...JRF...
James R. Ferguson
Acclaimed Contributor

Re: read file data into a variable

Hi Eevin:

I think you will find the input redirection is faster than spawning 'cat' to read the file and capture the first line into your variable.

In fact, this is documented in the 'sh-posix' man pages:

/begin_quote/

The command substitution $(cat file) can be replaced by the equivalent but faster $(
/end_quote/

...while I am an animal lover, including mmembers of the feline species, I avoid cat's whenever possible! :-;

Regards!

...JRF...