Linux Shell on the line in the file, words, characters iterate

During processing text files, file pieces in the line, words, characters and iterative traversal is very common operations. And for a simple loop iteration, plus redirect stdin or from a file, which is the basic iterative methods for file lines, words, and characters.

Ado, immediately take a look at how to achieve it.

1, the text of each line iteration
using a while loop to read from standard input, to be read in as standard input, it is necessary to redirect the file, so that it is redirected to the stdin, as follows:

while read line;
do
echo $line;
done < file.txt

The first line of code read from stdin line, and the source of stdin file.txt, because the last line of data traffic redirection, the contents of file.txt to redirect stdin.

2, iterative row every word
we can use a for loop to iterate word line of code is as follows:

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

The first line of code, reads a line from stdin, then loop iteration all the words in a row with for, and output, is really very simple and practical.

3, each iteration a word in a character
iteration word from each character can be said that the three most difficult one iteration, because extracting the character requires a certain skill from the word, which is as follows:

Using a variable i for loop iteration, iterative ranges from 0 to -1 characters in length. How to remove the words that the characters do? We can use an expression that is taken out the i-th word letters, $ {string: count_of_characters: start_position} string, which means that the returned string STRING, starting from the start_position-character count_of_characters , one iteration for the first character in a word, of course, from the i-th character string returns a substring of length, which is the sub-string extraction techniques. So the code is as follows:

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

Note: $ {# word} return variable word length value, i.e., the length of the word.

 

Guess you like

Origin www.cnblogs.com/jiangzhaowei/p/11526974.html