如何根据名称模式合并文件

时间:2018-10-09 22:29:19

标签: bash shell unix cat

/myfiles/sandboxserver_local.tar.gz.part-aa
/myfiles/sandboxserver_local.tar.gz.part-ab
/myfiles/sandboxserver_local.tar.gz.part-ac

/myfiles/sandboxserver_shared.tar.gz.part-aa
/myfiles/sandboxserver_shared.tar.gz.part-ab
/myfiles/sandboxserver_shared.tar.gz.part-ac

/myfiles/sandboxserver_admin.tar.gz.part-aa
/myfiles/sandboxserver_admin.tar.gz.part-ab
/myfiles/sandboxserver_admin.tar.gz.part-ac

/myfiles/prodserver_local.tar.gz.part-aa
/myfiles/prodserver_local.tar.gz.part-ab
/myfiles/prodserver_local.tar.gz.part-ac

/myfiles/prodserver_shared.tar.gz.part-aa
/myfiles/prodserver_shared.tar.gz.part-ab
/myfiles/prodserver_shared.tar.gz.part-ac

/myfiles/prodserver_admin.tar.gz.part-aa
/myfiles/prodserver_admin.tar.gz.part-ab
/myfiles/prodserver_admin.tar.gz.part-ac

所有这些文件都存储在一个目录中。我想基于其名称模式合并这些文件,如sandboxserver_local.tar.gz,sandboxserver_shared.tar.gz,sandboxserver_admin.tar.gz,prodserver_local.tar.gz,prodserver_shared.tar.gz,prodserver_admin.tar.gz ... ........有人可以帮助...在此先感谢

2 个答案:

答案 0 :(得分:0)

#!/usr/bin/env bash

# loop over all files
for file in /myfiles/*.tar.gz.part*; do
   # remove last characters (".part-xx")
   # this creates filename.tar.gz
   tarball="${files%.part-[a-z][a-z]}"
   # if the tarball exists, move to the next
   [[ -f "${tarball}" ]] && continue
   # concatenate tar files
   cat ${tarball}.part-[a-z][a-z] > "${tarball}"
done

答案 1 :(得分:0)

find ./myfiles -type f -regex '.*/.*\.tar\.gz\.part-.*' |
sed 's/\.part-.*$//' | 
sort -u |
xargs -n1 -d'\n' -- \
sh -c 'cat "$1".part-* > "$1"' --

从名为myfiles的{​​{1}}文件夹中获取所有文件。 I从文件名中删除最后一个*.tar.gz.part-*,并从列表中仅获取唯一的文件名。然后,对于每一行,我都使用xargs运行.part-*

可通过tutorialspoint获得实时版本。