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

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

问题描述

假设我有两个字符串列表(列表 A 和列表 B),每个列表中的条目数完全相同,N,并且我想用 A 的第 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).

最有效的方法是什么?

一种低效的方法是对sed s/stringA/stringB/g"进行 N 次调用.

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天全站免登陆