====== Reading Lines From Files ====== ---- Links & references: * [[http://mywiki.wooledge.org/BashFAQ/001|Bash FAQ, Question #1]] * [[http://askubuntu.com/questions/344407/how-to-read-complete-line-in-for-loop-with-spaces|An askubuntu page on this topic]] * [[http://en.tldp.org/LDP/abs/html/internalvariables.html|Bash Internal Field Separator variable]] * [[http://en.kioskea.net/faq/1757-how-to-read-a-file-line-by-line|Summarizes the above]] ---- ===== While Read ===== The shell [[cs_370_-_shell_scripting#input_in_shell_scripts|read]] command inputs entire lines. We can do the following to send a file, line by line, to a // while read// loop: # Non-ideal method. # File we are going to process is represented by $filename. cat $filename | while read line; do echo $line # simple echo of each line done But [[http://linuxpoison.blogspot.com/2012/08/bash-script-how-read-file-line-by-line.html|some people]] have a problem with this. They say that you should instead do the following, which represents the "BEST" way to read a file line by line in a shell script: # BEST method. # File we are going to process is represented by $filename. while read line; do echo $line # simple echo of each line done < $filename ===== For Loop ===== For files that contain only one word or one field per line, where it is guaranteed that no white space characters will appear, a //for// loop can be used like this: # WORST method. # File we are going to process is represented by $filename. for line in $(cat $filename); do echo $line # simple echo of each line done This is considered the absolute [[http://linuxpoison.blogspot.com/2012/08/bash-script-how-read-file-line-by-line.html|"WORST"]] way to try to read a file, line by line. But a Bash internal variable [[http://en.tldp.org/LDP/abs/html/internalvariables.html|($IFS)]] (internal field separator) can mitigate this for files that contain more than one word per line. See examples at http://en.kioskea.net/faq/1757-how-to-read-a-file-line-by-line. ----