Computer Hope

Software => BSD, Linux, and Unix => Topic started by: BRIANH on May 12, 2010, 09:58:15 AM

Title: how to assign the contents of a file to a variable
Post by: BRIANH on May 12, 2010, 09:58:15 AM
I have the following code:

resdir='/opt/mydir1/client/13.01/mydir2/commandline'
echo $resdir > /usr/me/myfile.txt

I'd like to set the contents of /usr/me/myfile.txt to a variable. Is that possible?

Title: Re: how to assign the contents of a file to a variable
Post by: marvinengland on May 18, 2010, 10:58:25 AM
I have the following code:

resdir='/opt/mydir1/client/13.01/mydir2/commandline'
echo $resdir > /usr/me/myfile.txt

I'd like to set the contents of /usr/me/myfile.txt to a variable. Is that possible?


It is better to assign each token ( or line ) of file to an array element.  Awk and shell does arrays easily.

The following is a batch array:


C:\test>type varforfile.bat
Code: [Select]
@echo off
set n=1
setlocal enabledelayedexpansion
for /f "tokens=1-7 delims=,=" %%a in (test.txt) do (
set /a n=!n! + 1
if !n!==15 goto end
set var!n!=%%g
echo var!n!=%%g

)
:end
echo outside of loop
echo var12=%var12%

Output:

C:\test>varforfile.bat
var2= 269338
var3= 263941
var4= 266663
var5= 265108
var6= 268421
var7= 269602
var8= 266973
var9= 266477
var10= 270655
var11= 266822
var12= 268137
var13= 267681
var14= 266535
outside of loop
var12= 268137

C:\test>
Title: Re: how to assign the contents of a file to a variable
Post by: Geek-9pm on May 18, 2010, 01:28:23 PM
Quote
resdir='/opt/mydir1/client/13.01/mydir2/commandline'
echo $resdir > /usr/me/myfile.txt

That code could be for use on a Linux system
It would help if the OP would indicate what OS he has.
Title: Re: how to assign the contents of a file to a variable
Post by: Salmon Trout on May 18, 2010, 01:34:32 PM
Now marvin is posting batch files in the Unix section!  ::)
Title: Re: how to assign the contents of a file to a variable
Post by: marvinengland on May 18, 2010, 04:14:54 PM
That code could be for use on a Linux system
It would help if the OP would indicate what OS he has.

resdir='/opt/mydir1/client/13.01/mydir2/commandline'
echo $resdir > /usr/me/myfile.txt

The contents of myfile.tx  was already assigned to a variable, resdir .

The question does not make sense.

Unix allows the assignment with a set command: ( all that is needed is var=value )

resdir='/opt/mydir1/client/13.01/mydir2/commandline'