[英]Is it possible to put a pipeline in a variable
我有一个很长的管道,我经常在我的脚本中重复使用它,为了便于阅读,我想把管道放在一个变量中。 是否可以?
cat miami.tmp | grep -A5 "$date" | grep -A3 "$nexthour" | grep "celsius" | grep -E -o '[-]?[0-9].[0-9]' | head -n 1 >> miami.txt
我努力了
temperature=$( | grep -A5 "$date" | grep -A3 "$nexthour" | grep "celsius" | grep -E -
o '[-]?[0-9].[0-9]' | head -n 1 )
或者
temperature="| grep -A5 "$date" | grep -A3 "$nexthour" | grep "celsius" | grep -E -o '[-]?[0-9].[0-9]' | head -n 1"
但会收到错误消息,提示未找到命令。
这是使用 bash 的shell 函数的一个很好的例子。 您可以这样定义 function:
function temperature() { grep foo | grep bar | grep baz; }
只需确保最后一个命令以分号结尾。 您拨打 function
cat file.tmp | temperature
函数也可以有参数,使用通常的$1
、 $2
等符号访问,可以传入(空格分隔)到 function。
$ function hello() { echo "Hello $1!"; }
$ hello world
Hello world!
你应该把它放在 function 中。
temperature () {
grep -A5 "$date" |
grep -A3 "$nexthour" |
grep "celsius" |
grep -E -o '[-]?[0-9].[0-9]' |
head -n 1
}
也许您想将日期和小时作为参数。
temperature () {
grep -A5 "$1" |
grep -A3 "$2" |
grep "celsius" |
grep -E -o '[-]?[0-9].[0-9]' |
head -n 1
}
另外,这看起来非常想重构为 Awk。
temperature () {
awk -v date="$1" nexthour="$2" '
$0 ~ date { p=5 }
p && p-- && ($0 ~ nexthour) { p=3 }
p && p-- && /celsius/ { n = split($0, a, /[^-.0-9]/, a);
for(i=1; i<=n; ++i) if (a[i] ~ /^-?[0-9]\.[0-9]$/)
{ print(a[i]); exit }'
}
(未经测试,因为您不提供测试数据。我不得不猜测一些事情。如果您通过系统地循环日期和时间来调用它,也可能将其重构到 Awk 脚本中。)
用法:
temperature 2022-11-24 04 <miami.tmp >>miami.txt
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.