1. Exercises
Find all files with the suffix. txt in the/123 directory
- Bulk Modify. txt to. txt.bak
- Package all. bak files into 123.tar.gz
- The name of the batch restore file, that is, to remove the added. Bak again
2. Exercise Analysis
- The first thing to do is to find out the. txt end file, using the Find command.
- Packing commands can be done with tar CZVF, and the key is how to package all. bak files at the same time.
- Restoring a file name is a bit complicated, and the key is how to find the original file name.
3. Specific scripts
In the script has always been added to my analysis, you can see
[[email protected] 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.bakwhile read line ; do mv $line $line.bakdone</tmp/file.txt# 由于要压缩打包,所以,创建一个目录,将文件复制到这个目录,再打包# 用时间戳来区分目录d=`date +%Y%m%d%H%M%S`mkdir /tmp/123_$dfor f in `cat /tmp/file.txt`;do cp $f.bak /tmp/123_$ddone# 开始打包cd /tmptar czf 123.tar.gz ./123_$d# 恢复文件名for f in `cat /tmp/file.txt`;do mv $f.bak $fdone
Analysis
- If you just traverse the directory, find some kind of file, and then modify the file name, in fact, a command can be done:
find /usr/local/sbin/work -type f -name "*.txt" -print0 | xargs -d ‘\0‘ mv {} {}.bak
Note that the find path of the Find command needs to use an absolute path, not a relative path. If the Xargs command is followed, the-PRINT0 option is used to include some special file names that contain spaces and will not handle errors.
- A while loop in a script is also very common, saving the results temporarily in a file and then reading the processing through the while loop.
- You can see that the/tmp/file.txt file has been used multiple times in the script. Save the file ending in. txt to a file, and this approach hates to solve the 3rd question we raised in the exercise analysis.
- All of my. txt end files are in the/usr/local/src/sbin/work directory.
? If you do not have a. txt end file, you can use the following command to generate a bunch of experiments:
for i in `seq 30`;do touch $i.txt;done
? This allows you to generate 30. txt end files for the experiment.
4. Conclusion
Today's exercises help you review the Find command, the Xargs command, and the For loop, while the common use of the loop, the key is to learn the idea of dealing with the problem.
?
Daily Shell Exercises (05)--Batch package files