User Tools

Site Tools


cs:bash_language:read_files
Return to Home page

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

cs:bash_language:read_files [2019/12/04 11:30] (current)
zioskenz created
Line 1: Line 1:
 +====== Read files ======
 +**Concepts:​**\\
 +Read a file //​word-by-word//,​ //​line-by-line//,​ //​character-by-character//​.
 +
 +**Text:**\\
 +Implement a program that reads a file which name is passed through the command line. The file must be read //​word-by-word//,​ //​line-by-line//​ and //​character-by-character//​.
 +
 +**Example:​**\\
 +Given this input file:
 +<code txt file.txt>​
 +w1 w2
 +w3
 +</​code>​
 +
 +the program has to provide the following output:
 +<code bash>
 +$ ./​read_files.sh file.txt
 +WORD: w1
 +WORD: w2
 +WORD: w3
 +LINE: w1 w2
 +LINE: w3
 +CHAR: w
 +CHAR: 1
 +CHAR: 
 +CHAR: w
 +CHAR: 2
 +CHAR: 
 +CHAR: w
 +CHAR: 3
 +CHAR: 
 +</​code>​
 +
 +**Solution:​**\\
 +<code bash read_files.sh>​
 +#!/bin/bash
 +# Read a file word-by-word,​ line-by-line and character-by-character
 +
 +# word-by-word
 +for i in $(cat $1) ; do
 +    echo "WORD: $i"
 +done
 +#done > file_out.txt ​ # If I would like to redirect the output on the file "​file_out.txt"​
 +
 +# line-by-line
 +while read i ; do
 +  echo "LINE: $i"
 +done < $1
 +#done < $1 > file_out.txt ​     # If I would like to redirect the output on the file "​file_out.txt"​
 +
 +# character-by-character
 +while read -n 1 i ; do
 +      echo "CHAR: $i"
 +done < $1
 +</​code>​
 +
 +**Comments:​**\\
 +If all the output of the commands in a ''​while''​ or ''​for''​ statements has to be redirected into a file, for instance ''​file_out.txt'',​ the following syntax can be used:
 +<code bash>
 +while read i ; do
 +  echo "LINE: $i"
 +done < $1 > file_out.txt
 +</​code>​
 +In only the output of some commands has to be redirected to standard output, the following code can be used:
 +<code bash>
 +rm -f file_out.txt
 +while read i ; do
 +  echo "LINE: $i" >> file_out.txt
 +  echo "Not redirected in file"
 +done < $1
 +</​code>​
 +
 +
  

If you found any error, or if you want to partecipate to the editing of this wiki, please contact: admin [at] skenz.it

You can reuse, distribute or modify the content of this page, but you must cite in any document (or webpage) this url: https://www.skenz.it/cs/bash_language/read_files?rev=1575455455&do=diff
/web/htdocs/www.skenz.it/home/data/pages/cs/bash_language/read_files.txt ยท Last modified: 2019/12/04 11:30 by zioskenz

Privacy Policy