LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   How do I read from a file in BASH? (https://www.linuxquestions.org/questions/programming-9/how-do-i-read-from-a-file-in-bash-304652/)

vous 03-22-2005 07:25 AM

How do I read from a file in BASH?
 
Hello all,

I'm trying to do this (which works fine):


#!/usr/bin/bash

LIST="Jupiter Venus Mercury"
n=1
for planet in $LIST
echo $planet
echo $n
let "n += 1"

done

But instead of doing it from the list I provide: LIST="Jupiter Venus Mercury"
I would like it to read from a file that has a complete list.

What do I have to change so it reads from a file in BASH?

trevelluk 03-22-2005 07:48 AM

Change the first line to LIST=`cat planets.txt`

Where planets.txt contains:

Jupiter Venus Mercury Mars...

This'll also work with each planet on a new line.

TheLinuxDuck 03-22-2005 07:52 AM

Using command substitution, you can easily loop through the contents of a file. If the file will be more than one line, the only thing different you'll need to do is pipe the output of the file through tr and replace all newlines with spaces.

This will only work, though, if your file does not contain words that have spaces in them.

Code:

filename=./planetlist.txt
for planet in `cat "$filename" | tr '\n' ' '`; do
  echo $planet
done


jlliagre 03-22-2005 08:38 AM

Or simpler:
Code:

filename=./planetlist.txt
for planet in $(<$filename)
do
  echo $planet
done


bahadur 03-22-2005 06:51 PM

files can be easily read using the head command

check the man pages for the command head.


All times are GMT -5. The time now is 02:09 PM.