SoFunction
Updated on 2025-03-10

Example of iterative output of lines, words, and characters in a file by shell script

When processing text files, iterating and traversing lines, words, and characters in the file is a very common operation. And using a simple loop for iteration, plus redirection from stdin or file, is the basic way to iterate over lines, words, and characters in the file.

Without further ado, let’s see how to achieve it now.

1. Iterate every line in the text

Use a while loop to read from standard input, because to read in standard input, you need to redirect the file to redirect it to stdin, the code is as follows:

Copy the codeThe code is as follows:

while read line; 
do 
echo $line; 
done <  

The first line of the code reads a line from stdin, and the source of stdin is that because the last line is redirected with a data stream, the content is redirected to stdin.

2. Iterate over every word in a line

We can use a for loop to iterate over words in a line, the code is as follows:

Copy the codeThe code is as follows:

read line; 
for word in $line; 
do 
echo $word; 
done 

The first line of the code, reading a line from stdin, then iterating over all the words in a line with a for loop and outputting it is really simple and practical.

3. Iterate over every character in a word

Iterating every character from a word can be said to be the most difficult of these three iterations, because extracting characters from words requires certain skills, and the methods are as follows:

Iterate the variable i using a for loop, and iterates from 0 to the length of the character -1. So how do you take out the characters in the word? We can use a special expression to extract the i-th letter in the word, ${string:start_position:count_of_characters}, which means to return a string composed of count_of_characters characters from the start_position in the string string. For iterating the first character in a word, of course, it returns a substring of length 1 from the i-th character of the string. This is the substring extraction technology. So the code is as follows:

Copy the codeThe code is as follows:

for((i=0; i<${#word}; ++i)) 
do 
echo ${word:i:1}; 
done 

Note: ${#word} returns the length of the value of the variable word, that is, the length of the word.