用于捕获 csv 文件中的文件名和大小并在该文件上添加标头的 shell 脚本

用于捕获 csv 文件中的文件名和大小并在该文件上添加标头的 shell 脚本

我在某个文件夹中有许多 zip 文件。我想每天以 CSV 格式捕获文件名和文件大小,并将其放入 crontab 中,以便我可以每天进行报告,然后将其邮寄到每个报告中。

文件位于/somedirectory/archive/test

-rw-rw-r--+ 1 AAAA AAAA 9.3M May  30 17:09 XXXXX_20140530_0401_28.txt.gz
-rw-rw-r--+ 1 AAAA AAAA 9.3M May  30 17:09 XXXXX_20140530_0401_29.txt.gz
-rw-rw-r--+ 1 AAAA AAAA 9.3M May  31 17:09 XXXXX_20140531_0401_01.txt.gz

现在我想创建一个 cronjob 每天运行并捕获我们每天准备的相同 CSV。

例子test30052014.csv

"File Name","size","date"
"XXXXX_20140530_0401_28.txt.gz", "9.3","May 30"
"XXXXX_20140530_0401_29.txt.gz", "9.3","May 30"

test31052014.csv:

"File Name","size","date"
"XXXXX_20140531_0401_01.txt.gz", "9.3","May 31"

答案1

执行此操作的一个简单方法是放入一个脚本:

#!/bin/bash    
echo "File Name,Size,date" > /tmp/output_file
ls -l --time-style=+%m.%d.%Y /path/to/file |grep -v "^total|^d"|awk '{print $NF","$4","$5 }'  >> /tmp/output_file

这将删除 ls 开头的总和并排除目录。

答案2

干得好。

#!/bin/sh

# Go to where the files are located
cd /somedirectory/archive/test

# Save IFS variable (if needed) and set it to newline.
SAVEIFS=$IFS
IFS=$(echo -en "\n\b")

# List the files and for each one save the size, time and name. Then, save results.
echo '"File Name","size","date"' > output.csv
for line in `ls -lrt *.txt.gz`; do
        size=$(echo $line |awk -F ' ' '{print $5}');
        date=$(echo $line |awk -F ' ' '{print $6" "$7}');
        file=$(echo $line |awk -F ' ' '{print $9}');
        echo '"'$size'","'$date'","'$file'"' >> output.csv
done

# Return IFS to original status.
IFS=$SAVEIFS

code=$?
exit $code

结果:

$ cat output.csv 
"File Name","size","date"
"0","Jun 3","XXXXX_20140530_0401_28.txt.gz"
"0","Jun 3","XXXXX_20140530_0401_29.txt.gz"
"0","Jun 3","XXXXX_20140531_0401_01.txt.gz"

相关内容