0

我制作了一个 linux 脚本来将一组 pcap 文件压缩到一个文件夹中。它将超过 2 天的文件保存到 zip 文件中。zip 与当前时间和日期一起保存为 zip 的文件名。无论如何使用第一个和最后一个 pcap 文件作为 zip 文件的文件名。

#!/bin/bash
cd /mnt/md0/capture/DCN
#Limit of your choice
ulimit -s 32000
LIMIT=10
#Get the number of files, that has `*.pcap`
in its name, with last modified time 5 days      ago
NUMBER=$(find /mnt/md0/capture/dcn/ -maxdepth 1 -name "*.pcap" -mtime +5 | wc -l)
if [[ $NUMBER -gt $LIMIT ]]  #if number greater than limit
then
FILES=$(find /mnt/md0/capture/dcn/ -maxdepth 1 -name "*.pcap" -mtime +5)
#find the files
zip -j /mnt/md0/capture/dcn/capture_zip-$(date "+%b_%d_%Y_%H_%M_%S").zip $FILES
#zip them
rm $FILES
#delete the originals
ulimit -s 8192 #reset the limit
fi #end of if.
4

1 回答 1

1

One way would be to use shell arrays:

IFS=$'\n' FILES=($(find /mnt/md0/capture/dcn/ -maxdepth 1 -name "*.pcap" -mtime +5))
#find the files and put the paths into an array "FILES"

This puts all of the files with paths into the shell array "FILES" and takes into consideration blanks in file names. The order will be in whatever order find gives them.

To build the zip file name:

FIRSTNAME=${FILES[0]##*/}
LASTNAME=${FILES[${#FILES[@]}-1]##*/}
ZIPPREFIX="${FIRSTNAME%.*}-${LASTNAME%.*}"
#zip base name made from first and last file basenames

Here, FIRSTNAME=${FILES[0]##*/} yields the name of the file with extension, and ${FIRSTNAME%.*} removes the extension. It will strip off the path and file extension. (If you want to keep the file extension, you can use $FIRSTNAME.) The value ${#FILES[@]} is the number of files in the array. Thus, the somewhat messy-looking ${FILES[${#FILES[@]}-1]} represents the last file name in the array. And finally the extra little bit of ##*/ in ${FILES[${#FILES[@]}-1]##/*} removes the path, leaving the file name. Ultimately, ZIPPREFIX will be the first base name, a hyphen (-), and the last base name. You can use a different character other than hyphen if you wish.

zip -j /mnt/md0/capture/dcn/"$ZIPPREFIX"-$(date "+%b_%d_%Y_%H_%M_%S").zip "${FILES[@]}"
#zip them

This zips the files. Note that ${FILES[@]} provides all of the array elements.

rm "${FILES[@]}"
#remove all the files
于 2013-11-07T12:03:43.110 回答