[英]Is it possible to put a pipeline in a variable
I have a long pipeline that I'm constantly reusing in my script, and to make it easy to read I want to put the pipeline in a variable.我有一个很长的管道,我经常在我的脚本中重复使用它,为了便于阅读,我想把管道放在一个变量中。 Is it possible?
是否可以?
cat miami.tmp | grep -A5 "$date" | grep -A3 "$nexthour" | grep "celsius" | grep -E -o '[-]?[0-9].[0-9]' | head -n 1 >> miami.txt
I have tried我努力了
temperature=$( | grep -A5 "$date" | grep -A3 "$nexthour" | grep "celsius" | grep -E -
o '[-]?[0-9].[0-9]' | head -n 1 )
or或者
temperature="| grep -A5 "$date" | grep -A3 "$nexthour" | grep "celsius" | grep -E -o '[-]?[0-9].[0-9]' | head -n 1"
but get errors saying the commands weren't found.但会收到错误消息,提示未找到命令。
This is a good case for using bash's shell functions .这是使用 bash 的shell 函数的一个很好的例子。 You can define a function like this:
您可以这样定义 function:
function temperature() { grep foo | grep bar | grep baz; }
just make sure that the last command ends with a semicolon.只需确保最后一个命令以分号结尾。 You call the function with
您拨打 function
cat file.tmp | temperature
Functions can also have parameters, accessed with the usual $1
, $2
etc. notation, that can be passed in (space-separated) to the function.函数也可以有参数,使用通常的
$1
、 $2
等符号访问,可以传入(空格分隔)到 function。
$ function hello() { echo "Hello $1!"; }
$ hello world
Hello world!
You should put it in a function.你应该把它放在 function 中。
temperature () {
grep -A5 "$date" |
grep -A3 "$nexthour" |
grep "celsius" |
grep -E -o '[-]?[0-9].[0-9]' |
head -n 1
}
Maybe you want to make the date and the hour into parameters.也许您想将日期和小时作为参数。
temperature () {
grep -A5 "$1" |
grep -A3 "$2" |
grep "celsius" |
grep -E -o '[-]?[0-9].[0-9]' |
head -n 1
}
Separately, this looks like it desperately wants to be refactored to Awk.另外,这看起来非常想重构为 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 }'
}
(Untested, as you don't supply test data. I had to guess some things. If you are calling it by systematically looping over dates and hours, probably refactor that into the Awk script, too.) (未经测试,因为您不提供测试数据。我不得不猜测一些事情。如果您通过系统地循环日期和时间来调用它,也可能将其重构到 Awk 脚本中。)
Usage:用法:
temperature 2022-11-24 04 <miami.tmp >>miami.txt
Probably see also https://mywiki.wooledge.org/BashFAQ/050大概也可以看看https://mywiki.wooledge.org/BashFAQ/050
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.