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:
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:
#!/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