あるファイルの空白行を別のファイルの行に置き換える

あるファイルの空白行を別のファイルの行に置き換える

私は持っていますファイル1.csv

"word 1"
""
"word 3"
""
"word 5"
"word 6"

そしてファイル2.csv

"replacement text 1"
"replacement text 2"
"replacement text 3"
"replacement text 4"
"replacement text 5"
"replacement text 6"

file1に空の行(または ""のある行)があることを確認し、それをfile2の内容に置き換えるコマンドを探しています。

これ出力.csvしなければならない

"word 1"
"replacement text 2"
"word 3"
"replacement text 4"
"word 5"
"word 6"

ベストアンサー1

ファイルの行数が同じであると仮定します。paste最初のファイルのフィールドを無題の最初の列として使用し、2番目のファイルのフィールドを無題の2番目の列として使用してCSVレコードストリームを作成します。

$ paste -d , file1.csv file2.csv
"word 1","replacement text 1"
"","replacement text 2"
"word 3","replacement text 3"
"","replacement text 4"
"word 5","replacement text 5"
"word 6","replacement text 6"

それから私達は利用できますミラー最初のフィールドが空の場合、最初のフィールドを2番目のフィールドの値で更新します。

$ paste -d , file1.csv file2.csv| mlr --csv -N put 'is_empty($1) { $1 = $2 }'
word 1,replacement text 1
replacement text 2,replacement text 2
word 3,replacement text 3
replacement text 4,replacement text 4
word 5,replacement text 5
word 6,replacement text 6

is_empty()そのフィールドが入力で参照されているかどうかにかかわらず、すべての空のフィールドに対してテストが適用されます。

その後、最初のフィールドを切り取り(抽出)できます。

$ paste -d , file1.csv file2.csv| mlr --csv -N put 'is_empty($1) { $1 = $2 }' then cut -f 1
word 1
replacement text 2
word 3
replacement text 4
word 5
word 6

Millerは実際に引用する必要があるフィールドだけを引用します。 Millerにすべての出力フィールドを引用させるには、次のようにします--quote-all

$ paste -d , file1.csv file2.csv| mlr --csv -N --quote-all put 'is_empty($1) { $1 = $2 }' then cut -f 1
"word 1"
"replacement text 2"
"word 3"
"replacement text 4"
"word 5"
"word 6"

このようなことを間違いなく似たようなことをするawk使用awk

$ paste -d , file1.csv file2.csv| awk -F , '$1 == "\"\"" { $1 = $2 } { print $1 }'
"word 1"
"replacement text 2"
"word 3"
"replacement text 4"
"word 5"
"word 6"

おすすめ記事