2

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?

Ira
  • 547
  • 4
  • 13

3 Answers3

3

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"
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • Thanks, how can get the IP address in a variable though? – Ira Mar 07 '23 at 01:17
  • The same way you get any other output into a variable. https://stackoverflow.com/questions/4651437/how-do-i-set-a-variable-to-the-output-of-a-command-in-bash – Barmar Mar 07 '23 at 15:07
1

One option is to use sed:

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

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}')
nntrn
  • 416
  • 2
  • 7