Awk: Печать строк в обратном направлении с номером строки и количеством слов

Короткий ответ:

  1. Нет.
  2. Для некоторых дистрибутивов это так.

Длинный ответ:

Linux - это ядро, а не дистрибутив. Если вы используете дистрибутив вроде NixOS, легко иметь несколько версий одной и той же библиотеки, установленных одновременно.

0
09.02.2018, 02:16
1 ответ

Parte del error de código

El problema clave es que tiene el formato %d: %s, pero solo hay un argumento $ipara hacer coincidir los especificadores de formato, es decir, $icoincide con %dpero no con %s.

Una vez que cambias el script como tal:

#!/usr/bin/awk -f

BEGIN { print("<< Start of file >>"); }

NR>=3 && NR<=5 { 
    for (i = NF; i >= 1; i--)
        printf "%d: %s ", i,$i;
    print ""
    wordCount += NF;


}

END { printf "<< End of file: wordCount = %d >>\n", wordCount }

Entonces no hay error y produce una salida como tal:

$./awk_script.awk input.txt
<< Start of file >>
7: vehicle! 6: motor 5: a 4: tricycle, 3: a 2: bicycle, 1: A 
6: it! 5: reverse 4: you 3: it, 2: deserve 1: I 
5: more 4: more, 3: more, 2: presents; 1: Gimme 
<< End of file: wordCount = 18 >>

Corrección del código para que coincida con el comportamiento deseado

Sin embargo, su descripción fue:

I am to display lines 3-5 backwards of a file i have created and before the outputted line, the line number is to be displayed (i.e. line 3:)

Eso significa que antes de procesar cada campo usando el bucle for -, primero debe generar el número de línea:

#!/usr/bin/awk -f

BEGIN { print("<< Start of file >>"); }

NR>=3 && NR<=5 {
    printf "line %d:",NR; # display line number first
    for (i = NF; i >= 1; i--)
        printf " %s ", $i;
    print ""; 
    wordCount += NF;

}

END { printf "<< End of file: wordCount = %d >>\n", wordCount }

Que funciona como tal:

$./awk_script.awk input.txt
<< Start of file >>
line 3: vehicle!  motor  a  tricycle,  a  bicycle,  A 
line 4: it!  reverse  you  it,  deserve  I 
line 5: more  more,  more,  presents;  Gimme 
<< End of file: wordCount = 18 >>
1
28.01.2020, 02:43

Теги

Похожие вопросы