bash脚本中的awk脚本

时间:2014-07-16 08:58:14

标签: linux bash shell awk

我想在bash脚本中使用awk脚本。不知何故,它无法正常工作。

这是我的bash脚本:

 1 #!/bin/bash
 2
 3
 4 echo "In what file do you want to look?"
 5 read input
 6 input="1D-MA.mcr"
 7
 8 echo "What are you looking for?"
 9 read muster
10
11 echo "What is the new value?"
12 read newVal
13
14 echo "What is the name of the new file?"
15 read output
16 
18 awk -v muster="${muster}" value="${newVal}" replace.awk "$input" > "$output"

这是我的awk脚本

 1 #!/usr/bin/awk -f
 2
 3 $1 == "$!VARSET" && $2 ~ muster { split($2, tmp, "=");  $2=tmp[1] "=" value; print }
 4 $1 != "$!VARSET" || $2 !~ muster

现在bash脚本只需要获取awk脚本并将其写入输入文件前。

编辑:我找到了答案。

将bash脚本更改为:

 1 #!/bin/bash
 2
 3
 4 echo "In what file do you want to look?"
 5 read input
 6 input="1D-MA.mcr"
 7
 8 echo "What are you looking for?"
 9 read muster
10
11 echo "What is the new value?"
12 read newVal
13
14 echo "What is the name of the new file?"
15 read output
16 
18 awk -v muster="${muster}" value="${newVal}" -f replace.awk "$input" > "$output"

并删除了awk-script中的-f

 1 #!/usr/bin/awk 
 2
 3 $1 == "$!VARSET" && $2 ~ muster { split($2, tmp, "=");  $2=tmp[1] "=" value; print }
 4 $1 != "$!VARSET" || $2 !~ muster

1 个答案:

答案 0 :(得分:0)

要回答原始问题(如何在bash脚本中运行awk脚本),下面是一个如何将awk脚本嵌入bash代码的示例:

#!/bin/bash

echo "This is bash speaking ..."    

awk -f /dev/stdin << EOF    
   BEGIN { print "... and this is actually awk!"; }    
EOF    

echo " ... and now it's me again, bash :-)"