Link to home
Start Free TrialLog in
Avatar of Rohit Bajaj
Rohit BajajFlag for India

asked on

read a word from a file in linux shell script

hi,
I have a file named env
It contains only one word : staging/prod/...
I just want to read that word inside the file..
whats the best and easiest way to do it ?

Thanks
ASKER CERTIFIED SOLUTION
Avatar of simon3270
simon3270
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Rohit Bajaj

ASKER

thanks.
just one more thing
if there are two or say may be 3 or more
and i want to store each of them in different variables and use them later..
i am asking for 3 or more just for knowledge sake.
but my current case will probably require 2

first one will be stored in a variable flock-apps-xonfig
and second in port
just want to know also if there are multiple such lines then how to do it using array
It would be better if they were in the form you first used (e.g. PORT=8080) so you could use the awk statement, so the order of lines in the file would not matter.

If they are just the first, second and third lines, one way would be:
    flock_apps_xconfig=$(sed -n 1p env)
    port=$(sed -n 2p env)
    nextvar=$(sed -n 3p env)
(the "-n" stops sed printing out each line, and the "1p" means print out line 1).  You can do the same think with awk, as:
    port=$(awk 'NR == 2{print}')
but sed is a more lightweight program (I hate wasting CPU cycles!).

Another option, if you are sure that each line has just one word on it (no spaces) you can do
    set -- $(cat env)
That sets $1 to the value of the first line, $2 to the second and so on.

By the way, flock-apps-xonfig is not a valid variable name - hyphens now not allowed (they were in some early shells).

Edit: I was thinking of dots here - I don't think hyphens have ever been allowed
If you want to use an array, you could do something like:
   rsparr=($(cat env))
then use ${rsparr[0]} for the first line, ${rsparr[1]} for the second, ${rsparr[2]} for the third and so on.  This also asumes that each line has just one word on it.  The "sed" and "awk" solutions above work with lines, however many words there are on the line.