![用于捕获 csv 文件中的文件名和大小并在该文件上添加标头的 shell 脚本](https://linux22.com/image/37544/%E7%94%A8%E4%BA%8E%E6%8D%95%E8%8E%B7%20csv%20%E6%96%87%E4%BB%B6%E4%B8%AD%E7%9A%84%E6%96%87%E4%BB%B6%E5%90%8D%E5%92%8C%E5%A4%A7%E5%B0%8F%E5%B9%B6%E5%9C%A8%E8%AF%A5%E6%96%87%E4%BB%B6%E4%B8%8A%E6%B7%BB%E5%8A%A0%E6%A0%87%E5%A4%B4%E7%9A%84%20shell%20%E8%84%9A%E6%9C%AC.png)
我在某个文件夹中有许多 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"