在bash shell中管道和重定向

时间:2014-03-03 00:30:23

标签: linux bash shell

我想创建一个脚本来获取任何命中它的管道输出(此脚本将始终是最后一个脚本运行),将其保存到临时文件,然后删除临时文件作为脚本的最后一行。

示例:

cat blah | ./scripta.sh | ./anotherscript.sh | ./yetanotherscript |./finalscript

问题是我们并不总是一次运行所有脚本。一旦它可能是这样的:

cat blah | ./anotherscript.sh | ./finalscript.sh

cat blah | ./anotherscript.sh | yetanotherscript.sh | ./finalscript.sh

等...

脚本在将数据作为名为moo的文件抓取之后将像这样处理它

awk < moo 'NR%20==0 {print "\nYear  Eng Disp. Cyl  City FE  Hwy FE    Model\n" } {print}  END{ print "total lines: " NR}'

是否可以添加

rm -r \file\path\to\where\is\moo

作为最后一行?

1 个答案:

答案 0 :(得分:0)

默认情况下,'awk'实用程序从标准输入中读取,因此您可以将其放在shell脚本中:

#!/bin/bash

awk 'NR%20==0 {print "\nYear  Eng Disp. Cyl  City FE  Hwy FE    Model\n" } {print}  END{ print "total lines: " NR}'

你甚至可以写一个可执行的awk脚本和管道:

#!/usr/bin/awk

NR%20==0 {
  print "\nYear  Eng Disp. Cyl  City FE  Hwy FE    Model\n"
} 

{
  print
}

END { 
  print "total lines: " NR
}

使用此方法,听起来好像您不需要任何类型的临时文件。但是,如果你这样做,你也可以这样做:

#!/bin/bash

cat > /tmp/tmpfile.txt

# Do some things with the file.

rm /tmp/tmpfile.txt