使用 awk 将列转换为行
Convert columns to rows with awk
我有一个以下格式的输出文件。如何将其转换为第一列为 header 行,第二列为数据行的 csv?
输入:
"Node name","SLAVE_DB"
"Node ID","2"
"PostgreSQL version","10.17"
"Total data size","1 GB"
"Conninfo","host=192.168.0.1 port=5432 user=user dbname=postgres"
"Role","standby"
"WAL archiving","disabled (on standbys "archive_mode" must be set to "always" to be effective)"
期望的输出:
"Node name","Node ID","PostgreSQL version","Total data size","Conninfo","Role","WAL archiving"
"SLAVE_DB","2","10.17","1 GB","host=192.168.0.1 port=5432 user=user dbname=postgres","standby","disabled (on standbys ""archive_mode"" must be set to ""always"" to be effective)"
[编辑]
我通读了类似的问题并尝试了 awk -F "," '{ for (i=1;i<=NF;i++ ) printf $i ", " }'
但它不会产生所需的输出。我还想在数据中保留带引号的字段。
如果我们假设您的第一个字段(tag/name/header)中从来没有引号,那么在每个 Unix 机器上的任何 shell 中使用任何 awk:
$ cat tst.awk
BEGIN { FS=OFS="," }
{
tags[NR] =
vals[NR] =
}
END {
for ( colNr=1; colNr<=NR; colNr++ ) {
tag = tags[colNr]
printf "%s%s", tag, (colNr<NR ? OFS : ORS)
}
for ( colNr=1; colNr<=NR; colNr++ ) {
val = vals[colNr]
gsub(/^"|"$/,"",val)
gsub(/"/,"\"\"",val)
printf "\"%s\"%s", val, (colNr<NR ? OFS : ORS)
}
}
$ awk -f tst.awk file
"Node name","Node ID","PostgreSQL version","Total data size","Conninfo","Role","WAL archiving"
"SLAVE_DB","2","10.17","1 GB","host=192.168.0.1 port=5432 user=user dbname=postgres","standby","disabled (on standbys ""archive_mode"" must be set to ""always"" to be effective)"
如果您需要更多,请参阅 。
我有一个以下格式的输出文件。如何将其转换为第一列为 header 行,第二列为数据行的 csv?
输入:
"Node name","SLAVE_DB" "Node ID","2" "PostgreSQL version","10.17" "Total data size","1 GB" "Conninfo","host=192.168.0.1 port=5432 user=user dbname=postgres" "Role","standby" "WAL archiving","disabled (on standbys "archive_mode" must be set to "always" to be effective)"
期望的输出:
"Node name","Node ID","PostgreSQL version","Total data size","Conninfo","Role","WAL archiving" "SLAVE_DB","2","10.17","1 GB","host=192.168.0.1 port=5432 user=user dbname=postgres","standby","disabled (on standbys ""archive_mode"" must be set to ""always"" to be effective)"
[编辑]
我通读了类似的问题并尝试了 awk -F "," '{ for (i=1;i<=NF;i++ ) printf $i ", " }'
但它不会产生所需的输出。我还想在数据中保留带引号的字段。
如果我们假设您的第一个字段(tag/name/header)中从来没有引号,那么在每个 Unix 机器上的任何 shell 中使用任何 awk:
$ cat tst.awk
BEGIN { FS=OFS="," }
{
tags[NR] =
vals[NR] =
}
END {
for ( colNr=1; colNr<=NR; colNr++ ) {
tag = tags[colNr]
printf "%s%s", tag, (colNr<NR ? OFS : ORS)
}
for ( colNr=1; colNr<=NR; colNr++ ) {
val = vals[colNr]
gsub(/^"|"$/,"",val)
gsub(/"/,"\"\"",val)
printf "\"%s\"%s", val, (colNr<NR ? OFS : ORS)
}
}
$ awk -f tst.awk file
"Node name","Node ID","PostgreSQL version","Total data size","Conninfo","Role","WAL archiving"
"SLAVE_DB","2","10.17","1 GB","host=192.168.0.1 port=5432 user=user dbname=postgres","standby","disabled (on standbys ""archive_mode"" must be set to ""always"" to be effective)"
如果您需要更多,请参阅