Bash 从一个文件中获取值(通过awk)并在另一个文件中使用(通过sed)
我正在使用gawk从文件中获取一些值,但不是所有值。我有另一个文件,它是一个模板,我将使用它来替换某个部分,然后生成一个特定于我获取的那些值的文件。我想使用sed替换模板中的这些感兴趣的字段Bash 从一个文件中获取值(通过awk)并在另一个文件中使用(通过sed),bash,awk,sed,gawk,distinct-values,Bash,Awk,Sed,Gawk,Distinct Values,我正在使用gawk从文件中获取一些值,但不是所有值。我有另一个文件,它是一个模板,我将使用它来替换某个部分,然后生成一个特定于我获取的那些值的文件。我想使用sed替换模板中的这些感兴趣的字段 the dog NAME , likes to ACTION in water when he's bored 另一个文件f1将包含狗的名称和动作 Maxs,swim StoneCold,digs Thor,leaps 所以我可以获取这些值并将它们存储到关联数组中…我不能做的,或者
the dog NAME , likes to ACTION in water when he's bored
另一个文件f1将包含狗的名称和动作
Maxs,swim
StoneCold,digs
Thor,leaps
所以我可以获取这些值并将它们存储到关联数组中…我不能做的,或者说我看不到的是,如何将它们保存到我的sed脚本中?
所以一个简单的sed脚本可能是这样的
s/NAME/ value from f1
s/ACTION/ value from f1
所以我对模板的输出是
the dog Maxs , likes to swim in water when he's bored
因此,如果我运行一个bash文件,该命令看起来会像这样,或者像我所尝试的那样
gawk -f f1 animalNameAction | sed -f (is there a way to put something here) template | cat
gawk -f f1 animalNameAction > PulledValues| sed -f PulledValues template | cat
但所有这些都不起作用。因此,我想知道如何才能做到这一点 您可以使用
awk
本身来完成此操作
我假设,模板可以是多行字符
- 所以在
块中,我将整个文件(模板)内容保存在变量FNR==NR{}
中t
- 在另一个块中,我用逗号分隔的文件中的第一个和第二个字段替换了
和NAME
李>ACTION
$ cat template
the dog NAME , likes to ACTION in water when he's bored
$ cat file
Maxs,swim
StoneCold,digs
Thor,leaps
$ awk 'FNR==NR{ t = (t ? t RS :"") $0; next}{ s=t; gsub(/NAME/,$1,s); gsub(/ACTION/,$2,s); print s}' template FS=',' file
the dog Maxs , likes to swim in water when he's bored
the dog StoneCold , likes to digs in water when he's bored
the dog Thor , likes to leaps in water when he's bored
可读性更好:
awk 'FNR==NR{
t = (t ? t RS :"") $0;
next
}
{
s=t;
gsub(/NAME/,$1,s);
gsub(/ACTION/,$2,s);
print s
}
' template FS=',' file