加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > Linux > 正文

使用另一个文件作为转换列表,用AWK替换fileds

发布时间:2020-12-14 01:12:08 所属栏目:Linux 来源:网络整理
导读:我在 Windows中使用awk.我有一个名为test.awk的脚本. 此脚本应读取文件并使用值替换某个字段(键). key-值列表位于名为translate.txt的文件中. 它的结构是这样的: e;Emil f;Friedrichg;Gustafh;Heinrichi;Ida 在一个简单的例子中,我的输入文件将是 e,111 f,2
我在 Windows中使用awk.我有一个名为test.awk的脚本.
此脚本应读取文件并使用值替换某个字段(键).
key->值列表位于名为translate.txt的文件中.

它的结构是这样的:

e;Emil    
f;Friedrich
g;Gustaf
h;Heinrich
i;Ida

在一个简单的例子中,我的输入文件将是

e,111    
f,222
g,333
h,444
i,555
..

所以输出应该是

Emil,111
Friedrich,222
Gustaf,333
Heinrich,444
Ida,555
..

我所拥有的脚本使用用户函数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 

}

另一件事,FS是错误的,它只从第二行开始工作.

解决方法

这个简单的单线程就可以解决问题:

awk  'FNR==NR{a[$1]=$2;next}{print a[$1],$2}' FS=',|;' OFS=',' translate input
Emil,555

以脚本形式:

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
}

运行如下:

awk -f translate.awk translate.txt input.txt

您的脚本有很多错误,您应该阅读Effective AWK Programming.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读