什么是在Unix文件另一个列表替换字符串列表的有效途径? [英] What is an efficient way to replace list of strings with another list in Unix file?

查看:133
本文介绍了什么是在Unix文件另一个列表替换字符串列表的有效途径?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个字符串(名单A和名单B)使用完全相同的条目数,N,在每个列表中的两份名单,我想用的第n个元素,以取代A的第n个元素的所有实例的B在Unix中(最好使用bash脚本)的文件

Suppose I have two lists of strings (list A and list B) with the exact same number of entries, N, in each list, and I want to replace all occurrences of the the nth element of A with the nth element of B in a file in Unix (ideally using Bash scripting).

什么是做到这一点的最有效方法是什么?

What's the most efficient way to do this?

这是低效率的方法是从N调用 SED S / stringA / stringB / G

An inefficient way would be to make N calls to "sed s/stringA/stringB/g".

推荐答案

这将做一通。它读取和listA的成数组listB awk数组,然后为linput的每一行,它会检查每个字,如果这个词是在发现listA的,这个词是由数组listB相应的字代替。

This will do it in one pass. It reads listA and listB into awk arrays, then for each line of the linput, it examines each word and if the word is found in listA, the word is replaced by the corresponding word in listB.

awk '
    FILENAME == ARGV[1] { listA[$1] = FNR; next }
    FILENAME == ARGV[2] { listB[FNR] = $1; next }
    {
        for (i = 1; i <= NF; i++) {
            if ($i in listA) {
                $i = listB[listA[$i]]
            }
        }
        print
    }
' listA listB filename > filename.new
mv filename.new filename

我假设在为listA字符串不包含空格(awk的默认字段分隔符)

I'm assuming the strings in listA do not contain whitespace (awk's default field separator)

这篇关于什么是在Unix文件另一个列表替换字符串列表的有效途径?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆