Wednesday, November 30, 2011

Working them Files

Files can be read and written to in a number of ways in Unix, and shell programming
takes huge advantage of this.  Firstly, let's look at the basic input-output of a file.

$> echo "Write this to a file" > file.txt
$> echo "Write this, too!" >> file.txt
$> cat file.txt
write this to a file
write this, too!
$> echo "Overwrite the file with this!" > file.txt
$> cat file.txt
Overwrite the file with this!

As you can see, the > command tells the echo command to write the first line to
file.txt, and the >> command tells echo to add the words as a new line in the file. 
Each time we use the > command, it overwrites the entire file, replacing the contents.  
The >> simply adds new content as a new line to the end.

Not to sound too redundant, but let's try this in a loop:

while read line                #loop this while there is
                               #still a line to read
do                             #start the loop
                echo $line     #say the contents of the line
done < file.txt                #use this file.txt as the input

This crazy looking thing is best read almost backwards.  The file, called file.txt, is
input on the done line, one line of the file at a time.  When the while command tries to
read the file, it sees only one line of the file each time through the loop until there
are no more new lines.

Now let's imagine we have a file called example.txt that looks like this:

Jason 50 75
Groce 100 299

You can also store the name of the file in a variable and use the variable in place of
the file name after the < symbol.  Using the following while loop, we can manipulate
this a bit more.

filename="example.txt"                  #make a variable
                                                       
while read name num1 num2               #use the line from the
                                        #file to read variables
do                                      #start the loop
                echo "Name: $name"      #say the name
                echo "One: $num1"       #say the first number
                echo "Two: $num2"       #say the second number
done < filename                         #use example.txt to
                                        #input lines of variables

The output would look something like this:

Name: Jason
One: 50
Two: 75
Name: Groce
One: 100
Two: 299

Code away, techies!

No comments:

Post a Comment