-2

我有两个看起来像的文件:

**file1.txt**

"a","1","11","111"

"b","2","22","222"

"c","3","33","333"

"d","4","44","444"

"e","5","55","555"

"f","6","66","666"

**file2.txt**

"b"

"d"

"a"

"c"

"e"

"f"

我需要创建一个脚本来更改 的顺序file1并以file2. 例如:

"b","2","22","222"

"d","4","44","444"

"a","1","11","111"

"c","3","33","333"

"e","5","55","555"

"f","6","66","666"

我创建了一个如下所示的命令:

nawk '/^("b")/' file1 ; nawk '/^("d")/' file1 ; nawk '/^("a")/' file1 ; nawk '/^("c")/' file1 ; nawk '/^("e")/' file1 ; nawk '/^("f")/' file1

它可以解决问题,但是我想进一步自动化它,但不知道如何进行。我如何创建一个命令或变量来查看第 1 行file2("b")并将其放在上面的命令中,然后查看第 2 行file2("d")并将其放在上面的命令中,依此类推。基本上,如果可能的话,我希望命令查看文件 2 并填写上述命令中的空白。你们可以建议的任何其他更方便的命令将不胜感激。请注意,我目前必须在上述命令中手动插入文件 2 中的字母。

实际文件可能包含超过 100 行

4

1 回答 1

0
awk -F, 'NR==FNR { a[$1]=$0; next }
    ($1 in a) { print a[$1] }' file1 file2

这会将所有内容读file1入内存,然后按file2. 如果file1非常大,这可能不可行。

这是一个常见的 awk 习语;如果您需要更详细的解释,请搜索许多近乎重复的内容。

于 2013-10-01T19:27:48.100 回答