User Tools

Site Tools


cs:bash_language:read_files
Return to Home page

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:

file.txt
w1 w2
w3

the program has to provide the following output:

$ ./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: 

Solution:

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

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:

while read i ; do
  echo "LINE: $i"
done < $1 > file_out.txt

In only the output of some commands has to be redirected to standard output, the following code can be used:

rm -f file_out.txt
while read i ; do
  echo "LINE: $i" >> file_out.txt
  echo "Not redirected in file"
done < $1

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
/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