User Tools

Site Tools


cs:bash_language:read_files
Return to Home page
no way to compare when less than two revisions

Differences

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


cs:bash_language:read_files [2024/04/08 22:35] (current) – created - external edit 127.0.0.1
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?do=diff&rev2%5B0%5D=&rev2%5B1%5D=1575455455&difftype=sidebyside
/web/htdocs/www.skenz.it/home/data/pages/cs/bash_language/read_files.txt · Last modified: 2024/04/08 22:35 by 127.0.0.1

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki
Privacy Policy