在awk搜索中使用bash变量

时间:2018-08-09 15:12:41

标签: bash awk sed

嗨,我试图用另一个bash变量替换此代码

   awk -v val_shell="$shell_variable" -v name="$shell_variable2" '
/:$/{
  flag=""
}
/Backendapp/{
  flag=1
}
flag && NF && (/ImageTag:/){
  match($0,/^[[:space:]]+/);
  val=substr($0,RSTART,RLENGTH);
  $NF=val_shell;
  print val $0;
  next
}
1
'   Input_file

如何从bash中添加另一个变量来替换“ Backendapp”? 我尝试了$ 0〜name而不是/ Backendapp /,但是还是没有运气。

输入:

Backendapp:
  Name: spring-rest 
  Image: "testuser/backend"
  ImageTag: "latest"
  ImagePullPolicy: "Always"
  Port: 8080
  replicaCount: 2

Frontendapp:
  Name: spring-js
  Image: "testuser/frontend"
  ImageTag: "latest"
  ImagePullPolicy: "Always"
  replicaCount: 2

所需的输出:

Backendapp:
  Name: spring-rest 
  Image: "testuser/backend"
  ImageTag: "0.2.3"
  ImagePullPolicy: "Always"
  Port: 8080
  replicaCount: 2

Frontendapp:
  Name: spring-js
  Image: "testuser/frontend"
  ImageTag: "latest"
  ImagePullPolicy: "Always"
  replicaCount: 2

BASH变量:

shell_variable=0.2.3
shell_variable2=Backendapp

在此处尝试〜选项:

  awk -v val_shell="$shell_variable" -v name="$shell_variable2" '
/:$/{
  flag=""
}
$0 ~ name {
  flag=1
}
flag && NF && (/ImageTag:/){
  match($0,/^[[:space:]]+/);
  val=substr($0,RSTART,RLENGTH);
  $NF=val_shell;
  print val $0;
  next
}
1
'   Input_file

谢谢您的建议

1 个答案:

答案 0 :(得分:0)

您所拥有的似乎有效。也许您包含太多的正则表达式信息?

(pi4 525) $ match="l"
(pi4 526) $ (echo alpha;echo beta;echo gamma;echo delta) | awk -v var="$match" '$0 ~ var'
alpha
delta