我有一个文件,我必须在其中搜索一个单词,一旦找到该单词,我必须将该记录保留在我的输出中,并且我还需要从该记录返回并获取之前的记录,如下所示就是例子
insert_job: Capture this record as well job_type: FW
box_name:XXXXXXXXXXXXXXX
machine: XXXXXXXXXXXXXXX
owner: XXXXXXXXXXXXXXXXXXXXX
permission:
date_conditions: 0
description: "This job waits for .trg file of CRH load file. This job waits for 2 hrs and alarms Ops."
term_run_time: 121
box_terminator: 1
max_run_alarm: 120
alarm_if_fail: 1
profile: "XXXXXXXXXXXXX"
timezone: CentralTime
watch_file: "XXXXXXXXXXXXXXXXXXXXXXXXXX"
watch_interval: 30
在上面的 jil 中,一旦我找到 watch_file 关键字,我就需要返回并捕获 insert_job 部分中的作业名称。我的文件中有多个 jils,需要查找并写入输出文件。
答案1
使用awk
:
如果您想捕获包含关键字的整行:
awk '/^insert_job|^watch_file/' file
这也可以通过以下方式完成grep
:
grep -E '^insert_job|^watch_file' file
如果您只想捕获关键字insert_job:
和之后的字段watch_file:
,请使用选项-F
设置字段分隔符:
awk -F'[^ ]*: *' '/^insert_job/{a=$2}/^watch_file/{print a, $2}' file