行番号に基づいてファイルに列を追加する

行番号に基づいてファイルに列を追加する

他のファイルの最後に最後の列として追加したい数値のリストがあります。

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

前の数字(1、5、6)は、ターゲットファイルのどの行にこの数字を追加する必要があるかを示すため、最初の行が終わって.1965行目が終わる.964式です。paste file1 file2行番号は通常考慮されず、5行目ではなく1行目1:.196と2行目の末尾に.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

ベストアンサー1

そして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

おすすめ記事