How to read files in a script? This is a good operation
Review cat command
cat command: The cat command is used to connect files and print to the standard output device.
We create a new names.txt, which stores some names.
Using the cat command, you can see that the cat command lists the contents of the given file
cat 文件名
Use the value of the cat command as the return value
Let ’s write a script 1.sh and
do n’t forget to assign permissions to the file.
We can run 1.sh and see that the results of each line are printed in a space-separated form, which means we can use a for loop to traverse them.
Example 1 Read data from txt and create folders in a loop
[About the for loop: Shell script variables and process control ]
We modify the content of the script to
#!/bin/bash
names=$(cat ./names.txt)
for line in $names
do
mkdir $line
done
Run the script again, then the ls command, you can see that the name in the txt file is used to create the folder
Example 2, write txt
We create a txt file
Use the displacement operator to redirect file streams
Change the content of the script to the following. It is worth noting that after the echo, use the >> operator to redirect the output of the echo to the specified file
#!/bin/bash
names=$(cat ./names.txt)
for line in $names
do
echo $line >>./target.txt
done
Execute the script, and use the cat command to view the results, two >> is the additional content, and one> is the coverage content
Change two >> to one> You can see that the result is indeed covered