Iterating and traversing the lines, words, and characters in a file is a very common operation when you are working on a text file. Using a simple loop for iterations, plus a redirection from stdin or files, is the basic way to iterate through the lines, words, and characters in a file.
Do not say much nonsense, immediately to see how to achieve it.
1, each row in the iteration
Use a while loop to read from standard input, because to read in standard input, the file is redirected so that it is redirected to stdin, as follows:
Copy Code code as follows:
while read line;
Todo
Echo $line;
Done < file.txt
The first line of code reads a row from stdin, and the stdin source is file.txt, because the last line redirects with the data stream, redirecting the contents of the file.txt to stdin.
2, each word in the iteration line
We can use a for loop to iterate through a line of words, as follows:
Copy Code code as follows:
Read line;
for word in $line;
Todo
Echo $word;
Done
The first line of code, reading a row from stdin, and then iterating through all the words in a row with a For loop, and outputting, is really very simple and practical.
3, iterate each character in a word
Iterating each character from a word is one of the most difficult of the three iterations, because extracting characters from a word requires some skill, as follows:
The variable i is iterated using the For loop, with an iteration range from 0 to the length of the character-1. How do you remove the characters from the word? We can use a special expression to take out the first letter of the word, ${string:start_position:count_of_characters}, which means to return a string of strings, from the first Start_ Position a string of count_of_characters characters that, for the first character in a single word, is, of course, a substring of length 1, starting with the character of string, which is the substring extraction technique. So the code is as follows:
Copy Code code as follows:
for ((i=0; i<${#word}; ++i))
Todo
Echo ${word:i:1};
Done
Note: ${#word} returns the length of the value of the variable word, which is the length of the word.