附加到循环中的tar文件

时间:2015-04-09 17:41:41

标签: linux shell

我有一个目录,可能有6个文件。

team1_t444444_jill.csv
team1_t444444_jill.csv
team1_t444444_jill.csv
team1_t999999_jill.csv
team1_t999999_jill.csv
team1_t111111_jill.csv
team1_t111111_jill.csv

我希望能够根据t号对每个文件进行tar操作,因此t444444应该拥有自己的tar文件以及所有相应的csv。 t999999应该有它自己的等等......总共应该动态创建三个tar文件

for file in $bad_dir/*.csv; do
  fbname=`basename "$file" | cut -d. -f1`  #takes the pathfile off, only shows xxx_tyyyyy_zzz.csv
  t_name=$(echo "$fbname" | cut -d_ -f2)   #takes the remaning stuff off, only shows tyyyyy

  #now i am stuck on how to create a tar file and send email
  taredFile = ??? #no idea how to implement

  (cat home/files/hello.txt; uuencode $taredFile $taredFile) | mail -s "Failed Files" $t_name@hotmail.com

2 个答案:

答案 0 :(得分:1)

最简单的编辑脚本应该做你想做的事情。这可能是这样的。

for file in $bad_dir/*.csv; do
  fbname=`basename "$file" | cut -d. -f1`  #takes the pathfile off, only shows xxx_tyyyyy_zzz.csv
  t_name=$(echo "$fbname" | cut -d_ -f2)   #takes the remaning stuff off, only shows tyyyyy

  tarFile=$t_name-combined.tar
  if [ ! -f "$tarFile" ]; then
      tar -cf "$tarFile" *_${t_name}_*.csv
      { cat home/files/hello.txt; uuencode $tarFile $tarFile; } | mail -s "Failed Files" $t_name@hotmail.com
  fi
done

根据输入文件名的唯一位使用tar文件名。然后在创建该文件并发送电子邮件之前检查该文件是否存在(防止多次创建该文件并多次发送电子邮件)。

使用这些文件是可通过球化的事实来获取tar,以便从我们看到的第一个文件中归档它们。

您还会注意到我在管道中将(commands)替换为{ commands; }()强制使用子shell,但管道本身也是如此,因此没有理由(在这种情况下)仅为分组效果手动强制额外的子shell。

答案 1 :(得分:0)

这就是你想要的:

for i in `find  | cut -d. -f2 | cut -d_ -f1,2 | sort | uniq`;
do
 tar -zvcf $i.tgz $i*
 # mail the $i.tgz file
done

看看我的跑步:

$ for i in `find  | cut -d. -f2 | cut -d_ -f1,2 | sort | uniq`; do tar -zvcf $i.tgz $i*; done
team1_t111111_jill.csv
team1_t111111_jxx.csv
team1_t111111.tgz
team1_t444444_j123.csv
team1_t444444_j444.csv
team1_t444444_jill.csv
team1_t444444.tgz
team1_t999999_jill.csv
team1_t999999_jilx.csv
team1_t999999.tgz

ubuntu@ubuntu1504:/tmp/foo$ ls
team1_t111111_jill.csv  team1_t111111.tgz       team1_t444444_j444.csv  team1_t444444.tgz       team1_t999999_jilx.csv
team1_t111111_jxx.csv   team1_t444444_j123.csv  team1_t444444_jill.csv  team1_t999999_jill.csv  team1_t999999.tgz