When processing text files, It is very common to iterate and traverse rows, words, and characters in the files. A simple loop is used for iteration, coupled with redirection from stdin or a file. This is the basic method to iterate rows, words, and characters in the file. Let's talk a little bit about it. Let's take a look at how to implement it. 1. Each row in the iteration text Use the while loop to read from the standard input. to read from the standard input, you need to redirect the file to stdin, Code As follows:
While read line; doecho $ line; done <file.txt
The first line of the Code reads one line from stdin, and the second line of stdints is file.txt. For the last line, the content of file.txt is redirected to stdin with data redirection. 2. iterate every word in a row We can use the for loop to iterate the words in a row. The Code is as follows:
Read line; for word in $ line; doecho $ word; done
The first line of the Code reads a row from stdin, iterates all the words in a row using the for loop, and outputs them. This is very simple and practical. 3. iterate every character in a word Iterations of each character in a word are the most difficult of the three iterations, because extracting characters from a word requires some skills. The method is as follows: the for loop is used to iterate variable I. The iteration range is from 0 to the length of the character-1. How can we retrieve the characters in a word? We can use a special expression to retrieve the I-th letter in a word, $ {string: start_position: count_of_characters}, which means that the string is returned, A string consisting of count_of_characters starting from start_position. For the first character in a word to be iterated, of course, a substring of 1 is returned starting from the I character of string, this is the substring extraction technology. The Code is as follows:
For (I = 0; I <$ {# Word}; ++ I) doecho $ {word: I: 1}; done
Note: $ {# Word} returns the length of the variable word value, that is, the word length.