Sch*_*mas 5 awk replace user-defined-functions
我awk在Windows中使用.我有一个叫做的脚本test.awk.此脚本应读取文件并使用值替换某个字段(键).key-> value列表位于一个名为的文件中translate.txt.
它的结构是这样的:
e;Emil
f;Friedrich
g;Gustaf
h;Heinrich
i;Ida
Run Code Online (Sandbox Code Playgroud)
在一个简单的例子中,我的输入文件将是
e,111
f,222
g,333
h,444
i,555
..
Run Code Online (Sandbox Code Playgroud)
所以输出应该是
Emil,111
Friedrich,222
Gustaf,333
Heinrich,444
Ida,555
..
Run Code Online (Sandbox Code Playgroud)
我所拥有的脚本正在使用用户函数key2value来进行替换,但是我没有成功地将此函数translate.txt作为源提供另一个文件.看我的代码:
{
FS=","
d=key2value($1)
print d "," $2
}
function key2value(b)
{
#this should use another file, not the currently processed one
FILENAME="translate.txt"
begin
{
FS=";"
if ($1=b)
{
return $2
}
end
}
Run Code Online (Sandbox Code Playgroud)
另一件事,FS是错误的,它只从第二行开始工作.
这个简单的单线程就可以解决问题:
awk 'FNR==NR{a[$1]=$2;next}{print a[$1],$2}' FS=',|;' OFS=',' translate input
Emil,111
Friedrich,222
Gustaf,333
Heinrich,444
Ida,555
Run Code Online (Sandbox Code Playgroud)
以脚本形式:
BEGIN { # The BEGIN block is executed before the files are read
FS="[,;]" # Set the FS to be either a comma or semi-colon
OFS="," # Set the OFS (output field separator) to be a comma
}
FNR==NR { # FNR==NR only true when reading the first file
key2value[$1]=$2; # Create associative array of key,value pairs
next # Grab the next line in the first file
}
{ # Now in the second file, print looked up value and $2
print key2value[$1],$2
}
Run Code Online (Sandbox Code Playgroud)
运行如下:
awk -f translate.awk translate.txt input.txt
Run Code Online (Sandbox Code Playgroud)
你的脚本有很多错误,你应该阅读Effective AWK Programming.