Servidores

awk, cut, sort y uniq con logs y CSV: espacios repetidos, comillas, sort -n, uniq -c sin sort y CRLF, medido con mawk 1.3.4 y gawk 5.2.1

Publicado el 2 de diciembre de 2026Última revisión: 2 de diciembre de 202616 min de lectura

Resultado de la prueba

con mawk 1.3.4 20240123 y gawk 5.2.1, ambos dieron la misma salida en los casos de espacios, separadores múltiples y CRLF. En 3 líneas con espacios repetidos, `cut -d' ' -f2` devolvió 2 campos vacíos de 3, mientras que `awk '{print $2}'` dio b, e, h; `tr -s ' '` antes de cut también. En un log de 3 líneas, `$NF` dio sda1, started y s (la tercera línea tenía espacios al final, que awk ignora) y NF fue 8, 5 y 8. `-F'[;,]'` separó por dos caracteres (NF 4 y 4), mientras que `cut -d';,'` falló con "the delimiter must be a single character". En un CSV con 3 líneas y 2 con una coma entre comillas, `cut` y `awk -F,` partieron esas líneas en 4 campos (NF 4, 3, 4). Con FPAT, gawk dio "Smith, John", "Doe" y "Ruiz, Ana" con NF 3 en las tres, y mawk ignoró FPAT. `gawk --csv` no existe en 5.2.1 (imprimió el uso). Con sort sin -n, 10,100,2,25,9; con sort -n, 2,9,10,25,100 (y la cabecera "size" cuenta como 0). `uniq -c` sin sort dio 5 grupos de 1 con la entrada a b a b a; con sort, 3 a y 2 b. En un fichero CRLF de 31 bytes, `$2=="OK"` dio 0 coincidencias de 2 posibles en mawk y en gawk; con `sub(/\r$/,"")` o `RS="\r?\n"` dio 2, y en bash `[ "$s" = OK ]` dio 0 coincidencias de 2 hasta quitar el \r con `${s%$'\r'}`. No se probó busybox awk, otras versiones, locales distintos de C.UTF-8 con sort -n, ni ficheros grandes. Mismos resultados en 3 de 3 ejecuciones.

Contenido

Este artículo no contiene enlaces de afiliado.

Los scripts de administración parten líneas de logs y CSV con awk, cut, sort y uniq casi sin pensarlo, y los fallos no dan error: devuelven un campo vacío, un orden raro o un contador que no cuadra. Aquí se mide cada trampa con un dato pequeño y se prueba con las dos implementaciones de awk que trae Ubuntu, mawk y gawk. Si el orden de sort te cambia según el entorno, mira LC_ALL=C frente a C.UTF-8 en sort, comm, join y grep. Si lees líneas con un bucle de bash en vez de awk, while read, IFS y la última línea sin salto cubre otras pérdidas. Para ficheros con espacios o saltos de línea en el nombre, xargs -0 y nombres de fichero raros. Si el script que procesa el log corre desde cron, el entorno mínimo de cron, y para que un fallo no pase en silencio, set -e y pipefail en scripts de copia.

Condiciones: Ubuntu 24.04.5 LTS, Linux 7.0.0-1017-oracle, bash 5.2.21, LC_ALL=C.UTF-8, coreutils 9.4 (cut, sort, uniq). Se probaron las dos implementaciones, llamadas por su nombre: mawk 1.3.4 20240123 y GNU Awk 5.2.1. En este sistema /usr/bin/awk apunta a gawk, así que un awk sin más fue gawk; en Debian o Ubuntu mínimos puede ser mawk, y la diferencia solo importó en FPAT. Todo se hizo con ficheros de 3 a 5 líneas creados por el script en un directorio de mktemp -d que se borra al salir. El script se ejecutó 3 veces y la salida fue idéntica en las 3. No se probó busybox awk, macOS/BSD awk, otras versiones de mawk o gawk (gawk 5.3 trae --csv, que aquí no existe), sort -n en otros locales, ficheros grandes ni rendimiento, csvkit, miller ni column. El texto lo redacté con ayuda de una IA a partir de la salida del script, y las cifras salen de esas ejecuciones.

Salida de la ejecución 1

Idéntica en las ejecuciones 2 y 3. Cada línea con $ es un cat -A donde $ marca el fin de línea y ^M un \r.

Ubuntu 24.04.5 LTS; Linux 7.0.0-1017-oracle; bash 5.2.21
mawk: mawk 1.3.4 20240123
gawk: GNU Awk 5.2.1, API 3.2, PMA Avon 8-g1, (GNU MPFR 4.2.1, GNU MP 6.3.0)
cut: cut (GNU coreutils) 9.4; sort: sort (GNU coreutils) 9.4; uniq: uniq (GNU coreutils) 9.4
/usr/bin/awk -> /usr/bin/gawk
=== run 1 ===
[1] $NF and fields with spaces (log line: date time host LEVEL message words...):
  mawk: $4 per line: ERROR,INFO,WARN,; $NF per line: sda1,started,s,; NF per line: 8,5,8,
  mawk: message without first 4 fields: disk full on sda1$|started$|retry in 5 s$|
  gawk: $4 per line: ERROR,INFO,WARN,; $NF per line: sda1,started,s,; NF per line: 8,5,8,
  gawk: message without first 4 fields: disk full on sda1$|started$|retry in 5 s$|
[2] cut -d' ' vs awk with repeated spaces (line 'a  b   c', 3 lines):
  cut -d' ' -f2: $|e$|$|
  cut -d' ' -f2 empty outputs: 2 of 3
  mawk '{print $2}': b$|e$|h$|
  gawk '{print $2}': b$|e$|h$|
  tr -s ' ' | cut -d' ' -f2: b$|e$|h$|
  awk -F' ' (single space = default splitting) in mawk/gawk: b$|e$|h$| / b$|e$|h$|
  awk -F'[ ]' (one space exactly) in mawk/gawk: $|e$|$| / $|e$|$|
[3] multiple separators (line 'k1;v1,v2;k2'):
  mawk -F'[;,]' NF: 4,4,; $3: v2,z,
  gawk -F'[;,]' NF: 4,4,; $3: v2,z,
  cut -d';,' error: cut: the delimiter must be a single character
  tr ',' ';' | cut -d';' -f3: v2,z,
  mawk -F',' $3:   c$| ; -F', *' $3: c$|
  gawk -F',' $3:   c$| ; -F', *' $3: c$|
[4] quotes in CSV (3 lines; line 1 has a comma inside quotes):
  cut -d, -f2: "Smith$|"Doe"$|"Ruiz$|
  cut -d, -f3:  John"$|7$| Ana"$|
  mawk -F, NF per line: 4,3,4,; sum of $3: 7
  mawk FPAT='([^,]*)|("[^"]+")' $2 / NF: John",42 / 2$| / 1$|Ana",9 / 2$|
  gawk -F, NF per line: 4,3,4,; sum of $3: 7
  gawk FPAT='([^,]*)|("[^"]+")' $2 / NF: "Smith, John" / 3$|"Doe" / 3$|"Ruiz, Ana" / 3$|
  mawk FPAT on escaped quote line, $2: ""hi""",y$|
  gawk FPAT on escaped quote line, $2: "say ""hi"""$|
  gawk --csv: Usage: gawk [POSIX or GNU style options] -f progfile [--] file ...
[5] sort -n vs lexical (values 9 10 100 2 25, plus a header):
  sort: 10,100,2,25,9,size,
  sort -n: size,2,9,10,25,100,
  sort -n | tail -1 (header sorts as 0): 100; head -1: size
  sort -rn | head -1: 100; sort -r | head -1: size
  sort -t, -k2 (lexical on key): b,c,d,a, ; sort -t, -k2 -n: d,a,b,c,
  sort -n on 1.5 and 1,5 and 10: 1,5 1.5 10 
  sort -n on 5 10 1e2 (exponent): 1e2 5 10  ; sort -g: 5 10 1e2 
[6] uniq -c without sort (input a b a b a, then 5 words with 2 distinct):
  uniq -c: 1 a,1 b,1 a,1 b,1 a,
  sort | uniq -c: 3 a,2 b,
  sort | uniq -c | sort -rn | head -1: 3 a
  lines '9 x' and '10 y': plain sort first line: 10 y; sort -n first line: 9 x
  mawk '{c[$1]++} END{for(k in c) print k,c[k]}' | sort: a 3,b 2,
  gawk '{c[$1]++} END{for(k in c) print k,c[k]}' | sort: a 3,b 2,
[7] CRLF (file made on Windows: 3 lines 'id,status' ending in \r\n):
  bytes: 31; lines with \r: 4 of 4
  cut -d, -f2: status^M$|OK^M$|FAIL^M$|OK^M$|
  mawk -F, $2=="OK" count: 0; $2=="OK\r" count: 2; length($2) of line 2: 3
  mawk -F, sub(/\r$/,"") then $2=="OK" count: 2
  mawk RS='\r?\n' $2=="OK" count: 2
  mawk $NF with FS=',': status^M$|OK^M$|FAIL^M$|OK^M$|
  gawk -F, $2=="OK" count: 0; $2=="OK\r" count: 2; length($2) of line 2: 3
  gawk -F, sub(/\r$/,"") then $2=="OK" count: 2
  gawk RS='\r?\n' $2=="OK" count: 2
  gawk $NF with FS=',': status^M$|OK^M$|FAIL^M$|OK^M$|
  tr -d '\r' | awk count (gawk): 2
  sort | uniq -c on status column, CRLF vs LF mix:
    raw: 1 FAIL$|1 OK$|2 OK^M$|
    after tr -d: 1 FAIL$|3 OK$|
  bash [ "$x" = OK ] with x read from CRLF file: no-match,no-match,no-match,
  same with read ... s=${s%$'\r'}: match,no-match,match,

Lo que se ve

Qué significa

Para un log con espacios variables, awk '{print $N}' es lo que quieres y cut -d' ' no. Para un CSV con comas entre comillas, nada de lo medido aquí es fiable salvo gawk con FPAT, y solo para comillas sencillas; si el script puede correr en un sistema con mawk, mejor un parser CSV de verdad. Todo número que se ordena o se compara con sort necesita -n (o -g), y la cabecera hay que quitarla antes. uniq -c va siempre detrás de sort, o se cuenta con un array de awk. Y con ficheros que pueden venir de Windows, conviene quitar el \r en la entrada (tr -d '\r' o sub) antes de comparar, porque cut, awk -F, y read lo dejan en el último campo sin avisar. Todo esto son resultados con datos de 3 a 5 líneas; el comportamiento con ficheros reales de otros tamaños no se midió.

Script completo

#!/bin/bash
# awk, cut, sort, uniq on logs/CSV in admin scripts: spaces in fields, $NF, multiple separators,
# cut -d' ' vs awk with repeated spaces, quotes in CSV, sort -n vs lexical, uniq -c without sort, CRLF.
# Every awk case runs with both mawk and gawk (explicit binaries). Everything inside one mktemp -d dir, removed on exit.
# Usage: test-awk-cut-sort-csv-crlf.sh
set -u
export LC_ALL=C.UTF-8
T=$(mktemp -d /tmp/awkx.XXXXXX) || exit 1
trap 'rm -rf "$T"' EXIT
cd "$T" || exit 1
AWKS="mawk gawk"
echo "$(. /etc/os-release; echo "$PRETTY_NAME"); $(uname -sr); bash ${BASH_VERSINFO[0]}.${BASH_VERSINFO[1]}.${BASH_VERSINFO[2]}"
echo "mawk: $(mawk -W version 2>&1 | head -1)"
echo "gawk: $(gawk --version | head -1)"
echo "cut: $(cut --version | head -1); sort: $(sort --version | head -1); uniq: $(uniq --version | head -1)"
echo "/usr/bin/awk -> $(readlink -f /usr/bin/awk)"
vis(){ cat -A | tr '\n' '|'; echo; }

for r in 1 2 3; do
echo "=== run $r ==="

echo "[1] \$NF and fields with spaces (log line: date time host LEVEL message words...):"
printf '%s\n' '2026-12-02 10:00:01 web1 ERROR disk full on sda1' '2026-12-02 10:00:02 web1 INFO started' '2026-12-02 10:00:03 web1 WARN   retry   in 5 s ' > app.log
for a in $AWKS; do
  echo "  $a: \$4 per line: $($a '{print $4}' app.log | tr '\n' ',' ); \$NF per line: $($a '{print $NF}' app.log | tr '\n' ','); NF per line: $($a '{print NF}' app.log | tr '\n' ',')"
  echo "  $a: message without first 4 fields: $($a '{$1=$2=$3=$4=""; sub(/^ +/,""); print}' app.log | vis)"
done

echo "[2] cut -d' ' vs awk with repeated spaces (line 'a  b   c', 3 lines):"
printf 'a  b   c\nd e f\ng    h i\n' > sp.txt
echo "  cut -d' ' -f2: $(cut -d' ' -f2 sp.txt | vis)"
echo "  cut -d' ' -f2 empty outputs: $(cut -d' ' -f2 sp.txt | grep -c '^$') of $(wc -l < sp.txt)"
for a in $AWKS; do echo "  $a '{print \$2}': $($a '{print $2}' sp.txt | vis)"; done
echo "  tr -s ' ' | cut -d' ' -f2: $(tr -s ' ' < sp.txt | cut -d' ' -f2 | vis)"
echo "  awk -F' ' (single space = default splitting) in mawk/gawk: $(mawk -F' ' '{print $2}' sp.txt | vis) / $(gawk -F' ' '{print $2}' sp.txt | vis)"
echo "  awk -F'[ ]' (one space exactly) in mawk/gawk: $(mawk -F'[ ]' '{print $2}' sp.txt | vis) / $(gawk -F'[ ]' '{print $2}' sp.txt | vis)"

echo "[3] multiple separators (line 'k1;v1,v2;k2'):"
printf 'k1;v1,v2;k2\nx;y,z;w\n' > multi.txt
for a in $AWKS; do
  echo "  $a -F'[;,]' NF: $($a -F'[;,]' '{print NF}' multi.txt | tr '\n' ','); \$3: $($a -F'[;,]' '{print $3}' multi.txt | tr '\n' ',')"
done
echo "  cut -d';,' error: $(cut -d';,' -f2 multi.txt 2>&1 | head -1)"
echo "  tr ',' ';' | cut -d';' -f3: $(tr ',' ';' < multi.txt | cut -d';' -f3 | tr '\n' ',')"
printf 'a, b,  c\n' > comma_sp.txt
for a in $AWKS; do echo "  $a -F',' \$3: $($a -F',' '{print $3}' comma_sp.txt | vis) ; -F', *' \$3: $($a -F', *' '{print $3}' comma_sp.txt | vis)"; done

echo "[4] quotes in CSV (3 lines; line 1 has a comma inside quotes):"
printf '1,"Smith, John",42\n2,"Doe",7\n3,"Ruiz, Ana",9\n' > q.csv
echo "  cut -d, -f2: $(cut -d, -f2 q.csv | vis)"
echo "  cut -d, -f3: $(cut -d, -f3 q.csv | vis)"
for a in $AWKS; do
  echo "  $a -F, NF per line: $($a -F, '{print NF}' q.csv | tr '\n' ','); sum of \$3: $($a -F, '{s+=$3} END{print s}' q.csv)"
  echo "  $a FPAT='([^,]*)|(\"[^\"]+\")' \$2 / NF: $($a 'BEGIN{FPAT="([^,]*)|(\"[^\"]+\")"} {print $2 " / " NF}' q.csv | vis)"
done
printf 'x,"say ""hi""",y\n' > q2.csv
for a in $AWKS; do echo "  $a FPAT on escaped quote line, \$2: $($a 'BEGIN{FPAT="([^,]*)|(\"[^\"]+\")"} {print $2}' q2.csv | vis)"; done
echo "  gawk --csv: $(gawk --csv '{print $2}' q.csv 2>&1 | head -1)"

echo "[5] sort -n vs lexical (values 9 10 100 2 25, plus a header):"
printf 'size\n9\n10\n100\n2\n25\n' > n.txt
echo "  sort: $(sort n.txt | tr '\n' ',')"
echo "  sort -n: $(sort -n n.txt | tr '\n' ',')"
echo "  sort -n | tail -1 (header sorts as 0): $(sort -n n.txt | tail -1); head -1: $(sort -n n.txt | head -1)"
echo "  sort -rn | head -1: $(sort -rn n.txt | head -1); sort -r | head -1: $(sort -r n.txt | head -1)"
printf 'a,9\nb,10\nc,100\nd,2\n' > kv.csv
echo "  sort -t, -k2 (lexical on key): $(sort -t, -k2 kv.csv | cut -d, -f1 | tr '\n' ',') ; sort -t, -k2 -n: $(sort -t, -k2 -n kv.csv | cut -d, -f1 | tr '\n' ',')"
echo "  sort -n on 1.5 and 1,5 and 10: $(printf '10\n1.5\n1,5\n' | sort -n | tr '\n' ' ')"
echo "  sort -n on 5 10 1e2 (exponent): $(printf '5\n10\n1e2\n' | sort -n | tr '\n' ' ') ; sort -g: $(printf '5\n10\n1e2\n' | sort -g | tr '\n' ' ')"

echo "[6] uniq -c without sort (input a b a b a, then 5 words with 2 distinct):"
printf 'a\nb\na\nb\na\n' > u.txt
echo "  uniq -c: $(uniq -c u.txt | sed 's/^ *//' | tr '\n' ',')"
echo "  sort | uniq -c: $(sort u.txt | uniq -c | sed 's/^ *//' | tr '\n' ',')"
echo "  sort | uniq -c | sort -rn | head -1: $(sort u.txt | uniq -c | sort -rn | head -1 | sed 's/^ *//')"
echo "  lines '9 x' and '10 y': plain sort first line: $(printf '9 x\n10 y\n' | sort | head -1); sort -n first line: $(printf '9 x\n10 y\n' | sort -n | head -1)"
for a in $AWKS; do echo "  $a '{c[\$1]++} END{for(k in c) print k,c[k]}' | sort: $($a '{c[$1]++} END{for(k in c) print k,c[k]}' u.txt | sort | tr '\n' ',')"; done

echo "[7] CRLF (file made on Windows: 3 lines 'id,status' ending in \\r\\n):"
printf 'id,status\r\n1,OK\r\n2,FAIL\r\n3,OK\r\n' > w.csv
echo "  bytes: $(wc -c < w.csv); lines with \\r: $(grep -c $'\r' w.csv) of $(wc -l < w.csv)"
echo "  cut -d, -f2: $(cut -d, -f2 w.csv | vis)"
for a in $AWKS; do
  echo "  $a -F, \$2==\"OK\" count: $($a -F, '$2=="OK"' w.csv | wc -l); \$2==\"OK\\r\" count: $($a -F, '$2=="OK\r"' w.csv | wc -l); length(\$2) of line 2: $($a -F, 'NR==2{print length($2)}' w.csv)"
  echo "  $a -F, sub(/\\r\$/,\"\") then \$2==\"OK\" count: $($a -F, '{sub(/\r$/,"")} $2=="OK"' w.csv | wc -l)"
  echo "  $a RS='\\r?\\n' \$2==\"OK\" count: $($a -F, 'BEGIN{RS="\r?\n"} $2=="OK"' w.csv | wc -l)"
  echo "  $a \$NF with FS=',': $($a -F, '{print $NF}' w.csv | vis)"
done
echo "  tr -d '\\r' | awk count (gawk): $(tr -d '\r' < w.csv | gawk -F, '$2=="OK"' | wc -l)"
echo "  sort | uniq -c on status column, CRLF vs LF mix:"
printf 'OK\r\nOK\nOK\r\nFAIL\n' > mix.txt
echo "    raw: $(sort mix.txt | uniq -c | sed 's/^ *//' | vis)"
echo "    after tr -d: $(tr -d '\r' < mix.txt | sort | uniq -c | sed 's/^ *//' | vis)"
echo "  bash [ \"\$x\" = OK ] with x read from CRLF file: $(while IFS=, read -r i s; do [ "$s" = OK ] && echo match || echo no-match; done < <(tail -n +2 w.csv) | tr '\n' ',')"
echo "  same with read ... s=\${s%\$'\\r'}: $(while IFS=, read -r i s; do s=${s%$'\r'}; [ "$s" = OK ] && echo match || echo no-match; done < <(tail -n +2 w.csv) | tr '\n' ',')"
done

Este artículo no contiene enlaces de afiliado.