Jump to content
  • Announcements

    • spinynorman

      Mandriva Official Documentation

      Official documentation for extant versions of Mandriva can be found at doc.mandriva.com.   Documentation for the latest release may take some time to appear there. You can install all the manuals from the main repository if you have Mandriva installed - files are prefixed mandriva-doc.
    • paul

      Forum software upgrade   10/29/17

      So you may have noticed the forum software has upgraded !!!
      A few things that have changed. We no longer have community blogs (was never really used) We no longer have a portal page.
      We can discuss this, and decide whether it is needed (It costs money) See this thread: Here
Sign in to follow this  
santner

reading a text file, line by line with bash

Recommended Posts

Bash is awesome, the only problem I have is that I have yet to find a simple way to read a basic text file from within a bash script one line at a time. For example, say my text file contains:

 

'Christmas Eve'

'Christmas Morning'

'New Years Eve'

 

So from my bash script I would like to be able to read each entire line, one at a time and save it to a variable within the script. I have googled and still can't find the answers. Please help! :D

Share this post


Link to post
Share on other sites

At first thought I can type two ways, I prefer the former because it doesn't use external commands:

while read line; do 
   echo $line # or whaterver you want to do with the $line variable
done < FILE

 

or

 

cat FILE | while read line; do 
   echo $line # or whaterver you want to do with the $line variable
done

 

hth

Share this post


Link to post
Share on other sites

Here is another example that has come up to my mind, this time I'm using the Field separator variable (IFS) set to "new line", and an array to store each line of the file into a field of an array named "lines":

old_IFS=$IFS
IFS=$'\n'
lines=($(cat FILE)) # array
IFS=$old_IFS

 

hence you can call each line by asking for its relative number:

echo ${line[4]} # will echo line number 4 (line numbering start with 0)

echo ${line[@]} # will print all the lines.

echo ${line[#]} # will print the size of the array (the total line numbering)

 

there are many other ways, just use the one that better fits your needs

 

 

hth

Edited by aru

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
Sign in to follow this  

×