AWK或sed以表格格式打印数据

问题描述 投票:0回答:1

我有如下数据。

Row: 1
Name    :   Ajay
Age     :   45
Address :   zyx

Row: 2
Name    :   Ajay
Age     :   45
Address :   zyx

Row: 3
Name    :   Ajay
Age     :   45
Address :   zyx

Row: 4
Name    :   Ajay
Age     :   45
Address :   zyx

我想要如下所示的输出。

Name    Age     Address
-----   ----    -------
Ajay    45      xyz
Ajay    45      xyz
Ajay    45      xyz
Ajay    45      xyz

姓名、年龄和地址列只是举例,它应该是任何内容和任何数字。 因此命令应该动态读取列并打印,并以相同的方式读取数据并打印

我尝试了下面的代码

#!/bin/bash

get_column_names() {
    # Extract column names from Row: 1 and Row: 2
    sed -n '/Row: 1/{n;p;q}' "$1" | awk -F '[:\t]' '{for(i=1;i<=NF;i+=2) print $i}'
}

print_header() {
    printf "%s\t" "$@"
    printf "\n"
}

data_file="ab.txt"

# Get col names
header=$(get_column_names "$data_file")

print_header $header

# Read data from file and print each row
max_row=$(grep -c "Row:" "$data_file")
for ((i=1; i<=$max_row; i++)); do
    sed -n "/Row: $i/{n;p;}" "$data_file" | awk -F '[:\t]' '{for(i=2;i<=NF;i+=2) printf "%s\t", $i; printf "\n"}'
done
unix awk sed paste
1个回答
0
投票

您可以使用这个

awk

awk -v OFS="\t\t" -F '[[:blank:]]*:[[:blank:]]*' '
NF && $1 != "Row" {
   row[++c] = $2
   if (!first)
      hdr[c] = $1
}
!NF {
   if (!first) {
      for (i=1; i<=c; ++i)
         printf "%s", hdr[i] (i < c ? OFS : ORS)
      for (i=1; i<=c; ++i)
         printf "%s", "-------" (i < c ? OFS : ORS)
      first = 1
   }
   for (i=1; i<=c; ++i)
      printf "%s", row[i] (i < c ? OFS : ORS)
   c = 0
 END {
   for (i=1; i<=c; ++i)
      printf "%s", row[i] (i < c ? OFS : ORS)
}' file

Name        Age     Address
-------     -------     -------
Ajay        45      zyx
Ajay        45      zyx
Ajay        45      zyx
Ajay        45      zyx
© www.soinside.com 2019 - 2024. All rights reserved.