Text-Processing

根據行號將列附加到文件

  • March 7, 2020

我有一個數字列表,我想將其添加到另一個文件的末尾作為最後一列:

1:.196
5:.964
6:.172

前面的數字(1,5 和 6)表示數字必須附加到目標文件的哪一行,因此第一行以 結尾.196,第五行以.964等等。通常paste file1 file2不考慮行號,只是1:.196在第一行.964的末尾和第二行的末尾而不是第五行的末尾添加。任何想法如何以正確的方式做到這一點?

預期會是這樣的:

Lorem Ipsum 1238 Dolor Sit 4559.196
Lorem Ipsum 4589 Sit elitr 1234
Lorem Ipsum 3215 Dolor Sit 5678
Lorem Ipsum 7825 Dolor Sit 9101
Lorem Ipsum 1865 Dolor Sit 1234.964

awk

# create two test files
printf '%s\n' one two three four five six > target_file
printf '%s\n' 1:.196 5:.964 6:.172 > numbers

awk -F':' 'NR==FNR{ a[$1]=$2; next } FNR in a{ $0=$0 a[FNR] }1' numbers target_file

輸出:

one.196
two
three
four
five.964
six.172

解釋:

awk -F':' '      # use `:` as input field separator
 NR==FNR {      # if this is the first file, then...
   a[$1]=$2     # save the second field in array `a` using the first field as index
   next         # stop processing, continue with the next line
 }                         
 FNR in a {     # test if the current line number is present in the array
   $0=$0 a[FNR] # append array value to the current line 
 }
 1              # print the current line
' numbers target_file

引用自:https://unix.stackexchange.com/questions/571586