cs:bash_language:read_files
Return to Home page
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
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 // | ||
+ | |||
+ | **Text:**\\ | ||
+ | Implement a program that reads a file which name is passed through the command line. The file must be read // | ||
+ | |||
+ | **Example: | ||
+ | Given this input file: | ||
+ | <code txt file.txt> | ||
+ | w1 w2 | ||
+ | w3 | ||
+ | </ | ||
+ | |||
+ | the program has to provide the following output: | ||
+ | <code bash> | ||
+ | $ ./ | ||
+ | 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: | ||
+ | <code bash read_files.sh> | ||
+ | #!/bin/bash | ||
+ | # Read a file word-by-word, | ||
+ | |||
+ | # word-by-word | ||
+ | for i in $(cat $1) ; do | ||
+ | echo "WORD: $i" | ||
+ | done | ||
+ | #done > file_out.txt | ||
+ | |||
+ | # line-by-line | ||
+ | while read i ; do | ||
+ | echo "LINE: $i" | ||
+ | done < $1 | ||
+ | #done < $1 > 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 '' | ||
+ | <code bash> | ||
+ | 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: | ||
+ | <code bash> | ||
+ | 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?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