Shell traverses files
Sometimes you have to do the same processing for all files under a certain folder, such as counting the number of lines for each file. At this time, it is very simple to use traversal of the files.
$ for i in `ls`;do wc -l $i;done
55552
55819
56118
56404
56633
56842
The for...do...done loop is used here. Note that when the loop statement is written on a line, it should be separated by ;.
ls should be expanded with backticks.
Shell traverses space text
Handling files containing spaces or special characters is something that everyone using Linux should have to master. In this article we will discuss how to use a for loop on a file with spaces.
The test text is as follows:
This line has spaces
these
do
not
Now, we use a for loop to iterate over this text. When we execute a for loop, the shell sees the spaces on the first line and assumes that each line is a different iteration.
[root@test ~]# for i in $(cat test);do echo $i;done This line has spaces these do not
IFS defines characters or character sets used as delimiters when separating words.
Wikipedia: For many command-line interpreters ("shell") of Unix operating systems, the internal field separator (IFS for short) refers to a variable that defines the characters used to split a pattern into a tag for certain operations.
By default, the value of IFS (field delimiter) is <space><tab><newline>. So when the shell sees the space in the first line, it divides the line into four markers (four words).
Modify the value of IFS to meet our needs
IFS is an environment variable. The best thing to do before changing environment variables is to save their contents. This makes it easy to set them to default values.
First, we save the value of the IFS variable to OLDIFS.
OLDIFS=$IFS
We can manually set IFS to any value we want. In this case, we need to use the field separator as a newline. We can set IFS like any variable.
IFS=<our value>
To set IFS to a newline, we can use the command replacement to get the newline output from the echo command.
IFS=`echo -e "\n"`
The output of echo -e "\n" is a newline character. For backtick encapsulation, the output of the shell command is used as the variable IFS.
Now, when we execute the same for loop, the shell will separate the text by a newline.
[root@test ~]# for i in $(cat test); do echo $i; done This line has spaces these do not
Translated fromLooping Through a File that Contains Spaces – Bash for Loop
Summarize
This is the end of this article about how Shell traverses space text. For more relevant Shell traverses space text, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!