Linux Admin - Read and Write to Files



Both reading and writing to files in BASH can done with the input and output redirectors. We have come across each in previous scripts.

#!/bin/bash 
myFile = "myLines.txt"

while read -a FILENAME; 
   do
   
   if [ `echo $FILENAME | grep 004` ]; 
      then 
      echo "line was $FILENAME" >> LineFile.txt 
      break 
   fi
   
echo $FILENAME 
done < $myFile

Instead of echoing to the terminal, our conditional branch now echoes to a file named LineFile.txt.

Reading from files has been presented in two ways, cat and read. read is usually always considered a best practice. While cat just passes the streams of text from a file. read implies to the script reading an actual file and takes accountability for a file being read.

The following script reads the text file again, puts each line into an array, then prints the array to the terminal.

#!/bin/bash 
myFile = "myLines.txt"
line = ()

while read -r FILELINE; 
   do 
   line+=($FILELINE) 
done < $myFile

for i in `seq 0 ${#line[@]}`; 
   do 
   echo $i " -> " ${line[$i]} 
done

Following is the output.

0  ->  line001 
1  ->  line002 
2  ->  line003 
3  ->  line004 
4  ->  line005 
5  ->  line006 
6  ->  line007 
7  ->  line008 
8  ->  line009
9  ->  line010
linux_admin_shell_scripting.htm
Advertisements