[英]Concatenate all files in one directory into one file, sorted by modification date, in Bash
[英]Bash - Concatenate files in a directory ordered by date
我需要一些簡單的腳本編寫幫助。 該腳本將包含以下文件的目錄作為輸入:
FILENAME20160220.TXT
FILENAME20160221.TXT
FILENAME20160222.TXT
...
該腳本需要將目錄作為輸入,並將其連接到一個名為的新文件中:
FILENAME.20160220_20160222.TXT
上面的文件名必須具有找到的“最早” _“最新”日期。 到目前為止,我編寫的腳本是這樣,但它不會產生必要的輸出。 有人可以幫我修補一下嗎?
declare FILELISTING="FILELISTING.TXT"
declare SOURCEFOLDER="/Cat_test/cat_test/"
declare TEMPFOLDER="/Cat_Test/cat_test/temp/"
# Create temporary folder
cd $SOURCEFOLDER
mkdir $TEMPFOLDER
chk_abnd $?
# Move files into temporary folder
mv *.TXT $SOURCEFOLDER $TEMPFOLDER
chk_abnd $?
# Change directory to temporary folder
cd $TEMPFOLDER
chk_abnd $?
# Iterate through files in temp folder and create temporary listing files
for FILE in $TEMPFOLDER
do
echo $FILE >> $FILELISTING
done
# Iterate through the lines of FILELISTING and store dates into array for sorting
while read lines
do
array[$i] = "${$line:x:y}"
(( i++ ))
done <$FILELISTING
# Sort dates in array
for ((i = 0; i < $n ; i++ ))
do
for ((j = $i; j < $n; j++ ))
do
if [ $array[$i] -gt $array[$j] ]
then
t=${array[i]}
array[$i]=${array[$j]}
array[$j]=$t
fi
done
done
# Get first and last date of array and construct output filename
OT_FILE=FILENAME.${array[1]}_${array[-1]}.txt
# Sort files in folder
# Cat files into one
cat *.ACCT > "$OT_FILE.temp"
chk_abnd $?
# Remove Hex 1A
# tr '\x1A' '' < "$OT_FILE.temp" > $OT_FILE
# Cleanup - Remove File Listing
rm $FILE_LISTING
chk_abnd $?
rm $OT_FILE.temp
chk_abnd $?
以下是一些提示, cat
完成大部分工作。 如果您的文件名具有固定大小的日期字段(如您的示例中所示),那么按詞法排序就足夠了。
ls -1 FILENAME* > allfiles
aggname=$(cat allfiles | sed -rn '1s/([^0-9]*)/\1./p;$s/[^0-9]*//p' |
paste -sd-)
cat allfiles | xargs cat > $aggname
您可以將最后兩個步驟組合為一個步驟,但這樣更易讀。
不要重新發明輪子。
假設可以使用FILENAME*.TXT
識別文件的基本列表,這很簡單,那么可以使用ls
生成一個有序列表,默認情況下,該列表將按字母順序升序排列(因此,由於您使用了日期格式按日期升序排列)。
您可以獲得最早和最晚的日期,如下所示:
$ earliest=$( ls -1 FILENAME*.TXT | head -1 | cut -c9-16 )
$ echo $earliest
20160220
$ latest=$( ls -1 FILENAME*.TXT | tail -1 | cut -c9-16 )
$ echo $latest
20160222
因此,可以使用以下命令生成您的文件名:
filename="FILENAME.${earliest}_${latest}.TXT"
串聯應該很簡單:
cat $( ls -1 FILENAME*.TXT ) > ${filename}
但是,如果您要寫入同一目錄,則可能希望先將輸出定向到不符合此模式的臨時名稱,然后重命名。 也許像這樣:
earliest=$( ls -1 FILENAME*.TXT | head -1 | cut -c9-16 )
latest=$( ls -1 FILENAME*.TXT | tail -1 | cut -c9-16 )
filename="FILENAME.${earliest}_${latest}.TXT"
cat $( ls -1 FILENAME*.TXT ) > temp_${filename}
mv temp_${filename} ${filename}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.