簡體   English   中英

AWK 與 $0 使用 sed 用新字符串替換模式

[英]AWK with $0 replace pattern with new string using sed

我有一個包含多個作業內容的文件,例如:

insert_job: 18132_TAL_D_DS_PEAR_AUTORECON   job_type: CMD 
command: $ADM_BIN/pear_generic_wrapper.ksh 
owner: gpadmin
permission: 

在這里,我需要為每個 insert_job 添加一行:

insert_job: 18132_TAL_D_DS_PEAR_AUTORECON   job_type: CMD 
condition: 18132_D_DS_PEAR_AUTORECON  

所以,基本上是 2 個步驟(首先復制行作業名稱;然后將18132_TAL_替換為18132_在打印為條件的第二個復制行中:)

為此,我 go 直到每個 insert_job 行的這一點:

insert_job: 18132_TAL_D_DS_PEAR_AUTORECON   job_type: CMD 
insert_job: 18132_TAL_D_DS_PEAR_AUTORECON 

現在,要更新第二行以將 insert_job 替換為條件,並將18132_TAL_替換為18132_ ,我被卡住了。

我正在嘗試編寫如下代碼:

$ cat input.dat | awk '($0!~"job_type") {print $0|sed "s/insert_job/condition/"} 1' 

但是,sed 在這里不起作用,它會給出語法錯誤。

您能否在print $0之后幫助使用 sed 的正確語法。

請您嘗試以下操作。

awk '
/insert_job/{
  val=$2
  sub(/_[^_]*/,"",val)
  $0=$0 ORS "condition: " val
  val=""
}
1
' Input_file

說明:為上述代碼添加說明。

awk '                            ##Starting awk code from here.
/insert_job/{                    ##Checking condition if string insert_job is found in a line then do following.
  val=$2                         ##Creating variable val whose value is $2(2nd field) of current line.
  sub(/_[^_]*/,"",val)           ##Substituting _ till next occurrence of _ with NULL in val here.
  $0=$0 ORS "condition: " val    ##Concatenating ORS(new line) then string condition and variable val here.
  val=""                         ##Nullifying variable val here.
}
1                                ##1 will print edited/non-edited line here.
'  Input_file                    ##Mentioning Input_file name here.

Output 將如下:

insert_job: 18132_TAL_D_DS_PEAR_AUTORECON   job_type: CMD 
condition: 18132_D_DS_PEAR_AUTORECON
command: /pear_generic_wrapper.ksh 
owner: gpadmin
permission: 

這是你想要做的嗎?

$ awk '
    { print }
    sub(/^insert_job/,"condition") {
        sub(/_TAL/,"")
        print $1, $2
    }
' file
insert_job: 18132_TAL_D_DS_PEAR_AUTORECON   job_type: CMD
condition: 18132_D_DS_PEAR_AUTORECON
command: $ADM_BIN/pear_generic_wrapper.ksh
owner: gpadmin
permission:

You never need sed when you're using awk and awk is not a shell, it's a completely separate tool with it's own language, syntax, and semantics so you shouldn't be trying to call other UNIX tools from it using shell syntax.

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM