What is an efficient way to replace list of strings with another list in Unix file?

前端 未结 6 505
礼貌的吻别
礼貌的吻别 2020-12-10 03:38

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

6条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-10 04:34

    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
    

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

提交回复
热议问题