awk - awk 在第一行末尾添加一个管道
问题描述
我的 awk 命令有点问题。
目标是在我的 CSV 中添加一个新列:
- 标头必须是“customer_id”
- 接下来的行必须是数组中的 customer_id
这是我的 csv :
email|event_date|id|type|cha|external_id|name|date
abcd@google.fr|2020-11-13 08:04:44|12|Invalid|Mail|disable|One|2020-11-13
dcab@google.fr|2020-11-13 08:04:44|13|Invalid|Mail|disable|Two|2020-11-13
我想要这个输出:
email|event_date|id|type|cha|external_id|name|date|customer_id
abcd@google.fr|2020-11-13 08:04:44|12|Invalid|Mail|disable|One|2020-11-13|20200
dcab@google.fr|2020-11-13 08:04:44|13|Invalid|Mail|disable|Two|2020-11-13|20201
但是当我做 awk 我有这个结果:
awk -v a="$(echo "${customerIdList[@]}")" 'BEGIN{FS=OFS="|"} FNR==1{$(NF+1)="customer_id"} FNR>1{split(a,b," ")} {print $0,b[NR-1]}' test.csv
email|event_date|id|type|cha|external_id|name|date|customer_id|
abcd@google.fr|2020-11-13 08:04:44|12|Invalid|Mail|disable|One|2020-11-13|20200
dcab@google.fr|2020-11-13 08:04:44|13|Invalid|Mail|disable|Two|2020-11-13|20201
其中 customerIdList = (20200 20201)
“customer_id”标题后面有一个管道,我不知道为什么:(有人可以帮我吗?
解决方案
您能否尝试使用显示的示例进行以下、编写和测试。
awk -v var="${customerIdList[*]}" '
BEGIN{
num=split(var,arr," ")
}
FNR==1{
print $0"|customer_id"
next
}
{
$0=$0 (arr[FNR-1]?"|" arr[FNR-1]:"")
}
1
' Input_file
说明:为上述添加详细说明。
awk -v var="${customerIdList[*]}" ' ##Starting awk program from here, creating var variable and passing array values to it.
BEGIN{ ##Starting BEGIN section of this program from here.
num=split(var,arr," ") ##Splitting var into arr with space delimiter.
}
FNR==1{ ##Checking condition if this is first line.
print $0"|customer_id" ##Then printing current line with string here.
next ##next will skip all further statements from here.
}
{
$0=$0 (arr[FNR-1]?"|" arr[FNR-1]:"") ##Checking condition if value of arr with current line number -1 is NOT NULL then add its value to current line with pipe else do nothing.
}
1 ##1 will print current line.
' Input_file ##Mentioning Input_file name here.
推荐阅读
- python - 启动器中的 Pip 致命错误:使用“”时无法创建进程
- flutter - 没有 FCM 的 Flutters Push Notifications 还是必须的?
- javascript - Node.js/Jest 测试 - expect(jest.fn()).toBeCalledWith()) 抛出有关“调用次数:0”的错误
- vuejs3 - 使用 quasar 框架在 vuex 模块中导入 vue-i18n
- javascript -
不与可见性折叠:折叠 - javascript - Vue:为什么计算属性在商店中声明时需要 v-model 指令中的 .value 而在组件中声明时不需要
- domain-driven-design - 聚合之间的共享枚举类 - 项目中的文件夹和文件结构
- python - 无法(手动)加载 cifar10 数据集
- jquery - 将箭头和样式滚动条添加到溢出容器
- javascript - 在 AXIOS 请求中捕获的未知类型