ICode9

精准搜索请尝试: 精确搜索
首页 > 系统相关> 文章详细

Linux从不同目录中递归查询相同文件并归档

2022-04-07 09:35:11  阅读:235  来源: 互联网

标签:target 递归 Linux file 归档 txt root class dir


描述

查找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

标签:target,递归,Linux,file,归档,txt,root,class,dir
来源: https://www.cnblogs.com/Torres-tao/p/16110763.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有