Linux从不同目录中递归查询相同文件并归档
2022/4/8 7:21:48
本文主要是介绍Linux从不同目录中递归查询相同文件并归档,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
描述
查找dest目录和source目录下相同的文件,打包成back_up.tar.gz
例:
dest |-1.txt |-2.txt |-lib |-1.class |-2.class |-3.class source |-1.txt |-3.txt |-2.class |-lib |-1.class |-4.class
则将1.txt lib/1.class打包到压缩包中
代码
function read_file(){ target_dir=$1 #清理遗留文件 rm -rf ${target_dir}.txt #遍历获取文件名,并输出到文本文件中 for file in $(ls ${target_dir}) do if [ -d ${target_dir}"/"${file} ];then read_file ${target_dir}"/"${file} else file_name=${target_dir}"/"${file} #${file_name#*/}表示去左留右,;${target_dir%%/*}表示去右留左,仅以首次传入的目录名来命名txt文件 echo ${file_name#*/} >> ${target_dir%%/*}.txt fi done } target_dir_1="dest" target_dir_2="source" #读取目录下文件信息 read_file ${target_dir_1} read_file ${target_dir_2} #获取相同文件(以${target_dir_1%%/*}.txt文件的每一行为关键字,查找${target_dir_2%%/*}.txt文件中匹配的行) grep -f ${target_dir_1%%/*}.txt ${target_dir_2%%/*}.txt > same_file.txt #将相同文件打包 pushd ${target_dir_1} #从文件清单中创建归档文件 tar -T ../same_file.txt -cvzf back_up.tar.gz popd
验证
[root@aliyun test]# tree dest/ dest/ ├── 1.txt ├── 2.txt └── lib ├── 1.class ├── 2.class └── 3.class 1 directory, 5 files [root@aliyun test]# tree source/ source/ ├── 1.txt ├── 2.class ├── 3.txt └── lib ├── 1.class └── 4.class 1 directory, 5 files [root@aliyun test]# sh find_same_file.sh LINE:1.txt LINE:lib/1.class [root@aliyun test]# ll 总用量 44 drwxr-xr-x 3 root root 4096 4月 7 09:10 dest -rw-r--r-- 1 root root 48 4月 7 09:10 dest.txt -rw-r--r-- 1 root root 1310 3月 11 15:57 find_same_file.sh -rw-r--r-- 1 root root 1477 3月 14 08:59 logs_select.sh -rw-r--r-- 1 root root 18 4月 7 09:10 same_file.txt drwxr-xr-x 3 root root 4096 3月 11 14:59 source -rw-r--r-- 1 root root 44 4月 7 09:10 source.txt -rw-r--r-- 1 root root 5953 4月 1 17:54 spiders_bs4.py -rw-r--r-- 1 root root 6318 4月 1 18:17 spiders_by_selemium.py [root@aliyun test]# cat dest.txt 1.txt 2.txt lib/1.class lib/2.class lib/3.class [root@aliyun test]# cat source.txt 1.txt 2.class 3.txt lib/1.class lib/4.class [root@aliyun test]# cat same_file.txt 1.txt lib/1.class
这篇关于Linux从不同目录中递归查询相同文件并归档的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-03-30[译]漫画SELinux概念
- 2024-03-29linux 移动文件
- 2024-03-28linux .so file
- 2024-03-28Linux 磁盘管理
- 2024-03-28Linux学习笔记(十三)磁盘管理(一):磁盘分区
- 2024-03-26linux 创建 文件
- 2024-03-25使用SecureCRT对Linux vim进行颜色设置
- 2024-03-202019-2020-12 20199317 《Linux内核原理与分析》 第十二周作业
- 2024-03-20Linux运维的第二周总结
- 2024-03-13how to count number of directories in linux