簡體   English   中英

如何使用Shell腳本從2個不同的文件中提取字段並將其存儲在輸出文件中?

[英]How to extract fields from 2 different files and store in an output file using shell script?

我發現以下命令有效。 但是有人可以解釋一下它的實際作用嗎?

awk 'NR==FNR{a[NR]=$2; next} {print a[FNR], $2}' file1 file2

它從文件中提取命令中傳遞的字段,並將其顯示在終端中。

awk 'NR==FNR{a[NR]=$2; next} {print a[FNR], $2}' file1 file2

由於NR代表當前輸入文件中的記錄號和FNR代表記錄號,所以在處理第一個文件時它們是相等的。 因此, awk 'NR==FNR { things1; next } { things2 }' file1 file2 awk 'NR==FNR { things1; next } { things2 }' file1 file2意思是:

  • 處理第一個文件時要做的things1 1。
  • 處理第二個文件時做的things2

a[NR]=$2; next a[NR]=$2; next意思是:

  • 將第二個字段存儲在數組a[] ,索引為記錄數(通常為行數,在這種情況下為行數)。

print a[FNR], $2表示:

  • 打印前一個文件的相應存儲字段以及當前文件的第二個字段。

這樣,這將產生並排包含兩個文件的第二個字段的輸出。

測試

$ cat f1
1 2 3
4 5 6
7 8 9
10 11 12
$ cat f2
a1 a2 a3
a4 a5 a6
a7 a8 a9
a10 a11 a12
$ awk 'NR==FNR{a[NR]=$2; next} {print a[FNR], $2}'  f1 f2
2 a2
5 a5
8 a8
11 a11

您可以在Idiomatic awk中找到更多信息。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM