Folosirea AWK pentru a parcurge un fisier si a transpune randuri in coloane

Configurare noua (How To)

Situatie

Ai nevoie sa convertesti/transpui textul dintr-un fisier (sau orice output) din randuri in coloane.

Spre exemplu avem fisierul "file.original.txt" de forma: 
R1_C1 R1_C2 R1_C3 R1_C4
R2_C1 R2_C2 R2_C3 R2_C4
R3_C1 R3_C2 R3_C3 R3_C4
R4_C1 R4_C2 R4_C3 R4_C4

Solutie

Pasi de urmat

Creare fisier de test:

cat << 'EOF' > file.original.txt
R1_C1 R1_C2 R1_C3 R1_C4
R2_C1 R2_C2 R2_C3 R2_C4
R3_C1 R3_C2 R3_C3 R3_C4
R4_C1 R4_C2 R4_C3 R4_C4
EOF

Afisare fisier original:

cat file.original.txt

Parcurge fisierul “file.original.txt” si a transpune randurile in coloane:

awk '{ for (i=1; i<=NF; i++) RtoC[i]= (RtoC[i]? RtoC[i] FS $i: $i) } END{ for (i in RtoC) print RtoC[i] }' file.original.txt
Mostra de resultat: 
--- output ---
cosadm@host: > cat << 'EOF' > file.original.txt
> R1_C1 R1_C2 R1_C3 R1_C4
> R2_C1 R2_C2 R2_C3 R2_C4
> R3_C1 R3_C2 R3_C3 R3_C4
> R4_C1 R4_C2 R4_C3 R4_C4
> EOF
cosadm@host: > cat file.original.txt
R1_C1 R1_C2 R1_C3 R1_C4
R2_C1 R2_C2 R2_C3 R2_C4
R3_C1 R3_C2 R3_C3 R3_C4
R4_C1 R4_C2 R4_C3 R4_C4
cosadm@host: > awk '{ for (i=1; i<=NF; i++) RtoC[i]= (RtoC[i]? RtoC[i] FS $i: $i) } END{ for (i in RtoC) print RtoC[i] }' file.original.txt
R1_C1 R2_C1 R3_C1 R4_C1
R1_C2 R2_C2 R3_C2 R4_C2
R1_C3 R2_C3 R3_C3 R4_C3
R1_C4 R2_C4 R3_C4 R4_C4
--- output ---

Tip solutie

Permanent

Voteaza

(14 din 28 persoane apreciaza acest articol)

Despre Autor

Leave A Comment?