我们可以运行一个数据透视表来在 linux 中将 1 条记录转换为多条记录吗

Ary*_*rya 3 text-processing

我们有如下数据

 ABC|RAM|BANGALORE|100,200,300
Run Code Online (Sandbox Code Playgroud)

我们可以运行任何数据透视/循环来将数据转换为多个记录吗

ABC|RAM|BANGALORE|100
ABC|RAM|BANGALORE|200
ABC|RAM|BANGALORE|300
Run Code Online (Sandbox Code Playgroud)

根据最后一列带有逗号分隔符的多个值,应创建记录数

我们有什么办法可以在 linux shell 中做吗?

ste*_*ver 7

我不会为此使用外壳本身。

另一个 awk 实现

$ awk 'BEGIN{OFS=FS="|"} {split($NF,a,","); for(i in a) {$NF = a[i]; print}}' data
 ABC|RAM|BANGALORE|100
 ABC|RAM|BANGALORE|200
 ABC|RAM|BANGALORE|300
Run Code Online (Sandbox Code Playgroud)

或与米勒

$ mlr --nidx --fs '|' nest --explode --values --across-records --nested-fs ',' -f 4 data
 ABC|RAM|BANGALORE|100
 ABC|RAM|BANGALORE|200
 ABC|RAM|BANGALORE|300
Run Code Online (Sandbox Code Playgroud)

或更紧凑

mlr --nidx --fs '|' nest --evar ',' -f 4 data
Run Code Online (Sandbox Code Playgroud)

如果您确实需要使用 shell,则使用适当的最新 bash:

#!/bin/bash

while IFS='|' read -a fields; do 
  IFS=',' read -a vals <<<"${fields[ -1]}"
  unset 'fields[ -1]'
  for v in "${vals[@]}"; do
    printf '%s|' "${fields[@]}" 
    printf '%s\n' "$v"
  done 
done < data
Run Code Online (Sandbox Code Playgroud)