R 9*_*000 3 shell bash find csv replace
我有file1.csv
"word 1"
""
"word 3"
""
"word 5"
"word 6"
Run Code Online (Sandbox Code Playgroud)
和file2.csv
"replacement text 1"
"replacement text 2"
"replacement text 3"
"replacement text 4"
"replacement text 5"
"replacement text 6"
Run Code Online (Sandbox Code Playgroud)
我正在寻找一个命令来检查 file1 中是否有空行(或带有“”的行),然后将其替换为 file2 的内容。
输出.csv应该是
"word 1"
"replacement text 2"
"word 3"
"replacement text 4"
"word 5"
"word 6"
Run Code Online (Sandbox Code Playgroud)
假设这些文件具有相同的行数:用于paste创建 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"
Run Code Online (Sandbox Code Playgroud)
如果第一个字段为空,我们可以使用Miller用第二个字段的值更新第一个字段:
$ 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
Run Code Online (Sandbox Code Playgroud)
对于任何空字段,测试is_empty()都将为 true,无论输入中是否引用了该字段。
然后我们可以剪切(提取)第一个字段:
$ 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
Run Code Online (Sandbox Code Playgroud)
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"
Run Code Online (Sandbox Code Playgroud)
您绝对可以使用 做类似的事情awk,但请记住,它awk不支持 CSV,会将双引号视为文字文本,因此会盲目地将每个逗号视为分隔符,即使它们嵌入在正确引用的字段中也是如此。它也不理解嵌入换行符的字段,但我们最初的假设已经排除了这些。
$ 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"
Run Code Online (Sandbox Code Playgroud)