Linux Shell scripts simply read and write files

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.
Insert picture description here
Insert picture description here
Using the cat command, you can see that the cat command lists the contents of the given file

cat 文件名

Insert picture description here

Use the value of the cat command as the return value

Let ’s write a script 1.sh and
Insert picture description here
Insert picture description here
do n’t forget to assign permissions to the file.
Insert picture description here
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.

Insert picture description here

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

Insert picture description here

Run the script again, then the ls command, you can see that the name in the txt file is used to create the folder
Insert picture description here

Example 2, write txt

We create a txt file
Insert picture description here

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

Insert picture description here
Execute the script, and use the cat command to view the results, two >> is the additional content, and one> is the coverage content
Insert picture description here

Change two >> to one> You can see that the result is indeed covered
Insert picture description here
Insert picture description here

Published 262 original articles · won 11 · 10 thousand views

Guess you like

Origin blog.csdn.net/weixin_44176696/article/details/105277306