アクティブなcrontabエントリの上に行を取得する方法

アクティブなcrontabエントリの上に行を取得する方法

次のcrontabエントリがあります

$ crontab -l
#Cron to auto restart app1
#Ansible: test1
#*/15 * * * * ansible-playbook  /web/playbooks/automation/va_action.yml


#Cron to auto restart app7

#Ansible: test7
*/15 * * * * ansible-playbook  /web/playbooks/automation7/va_action.yml | tee -a /web/playbooks/automation7/cron.out


#Cron to restart Apache services on automation server

#Ansible: test3
0 2 * * * /web/apps/prod/apache/http-automation/bin/apachectl -k start

以下はアクティブなcronエントリです。

crontab -l | grep  -v '#' | tr -d '\n'

*/15 * * * * ansible-playbook  /web/playbooks/automation7/va_action.yml | tee -a /web/playbooks/automation7/cron.out
0 2 * * * /web/apps/prod/apache/http-automation/bin/apachectl -k start

grep -B1私はそれがgrep文字列の上に行を与えることを知っています。

上記の説明に示すように、アクティブなcronエントリは次のとおりです。

#Ansible: test1
#Ansible: test7

だから私は次のように test1 と test7 を希望の出力としてリストしたいと思います。| awk '{print $2}'

希望の出力:

test1
test7

ベストアンサー1

awk処理された出力に対してすべての操作を実行するために使用できますcrontab -l

空白行を無視し、コメント化された行に関連するテキストをキャプチャし、追加の行を取得したら、キャプチャされたテキストを印刷するのがアイデアです。 2番目のフィールドだけが必要だと言われたので、そのフィールドだけを保存します。

crontab -l | awk '/^$/ { next ; }
                  /^#/ { text=$2 ; }
                  /^[^#]/ { print text; }'

書く方法はいくつかありますが、これが最も明確なようです。空の行、で始まる行#、で始まらない行を選択する3つのモードがあります。ただし、これはアクティブなcrontabの各エントリにコメントを付けるかどうかによって異なります。

おすすめ記事