A daily shell exercise (05) - batch packaging files

1. Exercises

Find all files with the suffix .txt in the /123 directory

  • Batch modify .txt to .txt.bak
  • Compress all .bak files into 123.tar.gz
  • Batch restore file names, that is, delete the added .bak

2. Problem Analysis

  1. First of all, find a way to find the files that end with .txt and use the find command.
  2. The packaging command can be done with tar czvf, the key is how to package all the .bak files at the same time.
  3. Restoring the filename is a bit complicated, the key is how to find the original filename.

3. Specific script

The script has always been added to my analysis, you can take a look

[root@cenvm71 work]# cat file_tar.sh 
#!/bin/bash

# 将符合条件的,以.txt 结尾的文件,保存到 /tmp/file.txt 
find /usr/local/sbin/work/ -maxdepth 1 -type f -name "*.txt" > /tmp/file.txt

# 用循环逐行读取 /tmp/file.txt 文件,修改文件名为 .txt.bak
while read line ; 
do
  mv $line $line.bak
done</tmp/file.txt

# 由于要压缩打包,所以,创建一个目录,将文件复制到这个目录,再打包
# 用时间戳来区分目录
d=`date +%Y%m%d%H%M%S`
mkdir /tmp/123_$d

for f in `cat /tmp/file.txt`;
do
  cp $f.bak   /tmp/123_$d
done

# 开始打包
cd /tmp
tar czf  123.tar.gz  ./123_$d

# 恢复文件名
for f in `cat /tmp/file.txt`;
do
  mv $f.bak $f
done

【analyze】

  1. If you just traverse the directory, find a certain file, and then modify the file name, you can actually do it with one command:
find  /usr/local/sbin/work  -type f -name "*.txt"  -print0 | xargs -d '\0'  mv {}  {}.bak

It should be noted that the search path of the find command needs to use an absolute path, not a relative path. If followed by the xargs command, use the -print0 option to include some special filenames containing spaces, and no error will be handled.

  1. The while loop in the script is actually very common. The result is temporarily saved in a file, and then read and processed through the while loop.
  2. You have seen that the file /tmp/file.txt is used many times in the script. Save the file ending in .txt to a file, this method solves the third problem we raised in the exercise analysis.
  3. All my files ending in .txt are in the /usr/local/src/sbin/work directory.

​ If you don't have files ending in .txt, you can use the following command to generate a bunch of them for experimentation:

for  i in `seq  30`;do  touch  $i.txt;done

​ In this way, 30 files ending in .txt can be generated for experiments.

4. Conclusion

Today's exercises help you review the find command, the xargs command, and the common usage of for loops and while loops. The key is to learn the way of dealing with problems.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325204386&siteId=291194637