提取 cron 作业的一部分

huangapple go评论53阅读模式
英文:

Bash extract part of the cron job

问题

我想提取cron作业中在--host参数之后出现的IP地址 -

34 15 * * * (cd /to/the/directory; ./my_program.pl  --param1  --host 198.181.111.222 --server 198.181.333.444 --version 1.0 --port 80 --user uid >> collect.log 2>&1)

问题是参数可以在cron中以随机顺序出现。我尝试使用cut,但仅当参数严格按顺序出现时才有效。

我尝试遵循一些Stack Overflow上的建议 -

str=$(crontab -l)
echo "${str}"
awk -F'--' '{ for(i=1;i<=NF;i++) print $i }' <<< $str

但这将str--拆分并将所有标记单独打印在不同的行上。

我们如何将198.181.111.222存储在变量$ip中?

英文:

I would like to extract the IP address that appears after --host param in the cron job -

34 15 * * * (cd /to/the/directory; ./my_program.pl  --param1  --host 198.181.111.222 --server 198.181.333.444 --version 1.0 --port 80 --user uid >> collect.log 2>&1)

Thing is the parameters can appear in random order in the cron. I tried using cut but that works only when the params are strictly in order.

I tried following some suggestions on SO -

str=$(crontab -l)
echo "${str}"
awk -F'--' '{ for(i=1;i<=NF;i++) print $i }' <<< $str

But this splits str by -- and prints all token on separate lines.

How can we store 198.181.111.222 in a variable $ip?

答案1

得分: 3

循环遍历该行的字段,直到找到--host。然后打印下一个字段。

英文:

Loop through the fields of the line until you get to --host. Then print the next field.

awk '{for (i = 1; i <= NF; i++) { if ($i == "--host") {print $(i+1); break} }' <<< "$str"

答案2

得分: 1

One option is to use sed:

ip=$(crontab -l | sed -n 's/^.*[[:space:]]--host[[:space:]][[:space:]]*\([^[:space:]][^[:space:]]*\).*$//p')
  • 这种方法只使用了 POSIX sed 的特性。
  • 如果 crontab -l 的输出包含两行或更多带有 --host 的内容,此方法将失败。
英文:

One option is to use sed:

ip=$(crontab -l | sed -n 's/^.*[[:space:]]--host[[:space:]][[:space:]]*\([^[:space:]][^[:space:]]*\).*$//p')
  • This uses only POSIX sed features.
  • It will fail if the crontab -l output contains two or more lines with --host in them.

答案3

得分: 1

使用grep!!!

$ crontab -l | grep -oE '--[a-z]+ [0-9.]+'
--host 198.181.111.222
--server 198.181.333.444
--version 1.0
--port 80

$ crontab -l | grep -oE '--host [0-9.]+'
--host 198.181.111.222

$ crontab -l | grep -oE '--host [0-9.]+' | awk '{print $2}'
198.181.111.222

设置$ip

ip=$(crontab -l | grep -oE '--host [0-9.]+' | awk '{print $2}')
英文:

Use grep!!!

$ crontab -l | grep -oE '\-\-[a-z]+ [0-9\.]+'
--host 198.181.111.222
--server 198.181.333.444
--version 1.0
--port 80

$ crontab -l | grep -oE '\-\-host [0-9\.]+'
--host 198.181.111.222

$ crontab -l | grep -oE '\-\-host [0-9\.]+' | awk '{print $2}'
198.181.111.222

Set $ip:

ip=$(crontab -l | grep -oE '\-\-host [0-9\.]+' | awk '{print $2}')

huangapple
  • 本文由 发表于 2023年3月7日 08:40:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/75657084.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定