From 05dba0fb2447c4969a2a92bdabd7d761bdcb9340 Mon Sep 17 00:00:00 2001 From: hugo Date: Sat, 15 Jul 2017 00:27:55 -0700 Subject: awk-es created --- es-es/awk-es.html.markdown | 361 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 361 insertions(+) create mode 100644 es-es/awk-es.html.markdown (limited to 'es-es/awk-es.html.markdown') diff --git a/es-es/awk-es.html.markdown b/es-es/awk-es.html.markdown new file mode 100644 index 00000000..7899fcb5 --- /dev/null +++ b/es-es/awk-es.html.markdown @@ -0,0 +1,361 @@ +--- +language: awk +filename: learnawk-es.awk +contributors: + - ["Marshall Mason", "http://github.com/marshallmason"] +translators: + - ["Hugo Guillén-Ramírez", "http://github.com/HugoGuillen"] +lang: es-es +--- + +AWK is a standard tool on every POSIX-compliant UNIX system. It's like a +stripped-down Perl, perfect for text-processing tasks and other scripting +needs. It has a C-like syntax, but without semicolons, manual memory +management, or static typing. It excels at text processing. You can call to it +from a shell script, or you can use it as a stand-alone scripting language. + +Why use AWK instead of Perl? Mostly because AWK is part of UNIX. You can always +count on it, whereas Perl's future is in question. AWK is also easier to read +than Perl. For simple text-processing scripts, particularly ones that read +files line by line and split on delimiters, AWK is probably the right tool for +the job. + +```awk +#!/usr/bin/awk -f + +# Comments are like this + +# AWK programs consist of a collection of patterns and actions. The most +# important pattern is called BEGIN. Actions go into brace blocks. +BEGIN { + + # BEGIN will run at the beginning of the program. It's where you put all + # the preliminary set-up code, before you process any text files. If you + # have no text files, then think of BEGIN as the main entry point. + + # Variables are global. Just set them or use them, no need to declare.. + count = 0 + + # Operators just like in C and friends + a = count + 1 + b = count - 1 + c = count * 1 + d = count / 1 + e = count % 1 # modulus + f = count ^ 1 # exponentiation + + a += 1 + b -= 1 + c *= 1 + d /= 1 + e %= 1 + f ^= 1 + + # Incrementing and decrementing by one + a++ + b-- + + # As a prefix operator, it returns the incremented value + ++a + --b + + # Notice, also, no punctuation such as semicolons to terminate statements + + # Control statements + if (count == 0) + print "Starting with count of 0" + else + print "Huh?" + + # Or you could use the ternary operator + print (count == 0) ? "Starting with count of 0" : "Huh?" + + # Blocks consisting of multiple lines use braces + while (a < 10) { + print "String concatenation is done" " with a series" " of" + " space-separated strings" + print a + + a++ + } + + for (i = 0; i < 10; i++) + print "Good ol' for loop" + + # As for comparisons, they're the standards: + a < b # Less than + a <= b # Less than or equal + a != b # Not equal + a == b # Equal + a > b # Greater than + a >= b # Greater than or equal + + # Logical operators as well + a && b # AND + a || b # OR + + # In addition, there's the super useful regular expression match + if ("foo" ~ "^fo+$") + print "Fooey!" + if ("boo" !~ "^fo+$") + print "Boo!" + + # Arrays + arr[0] = "foo" + arr[1] = "bar" + # Unfortunately, there is no other way to initialize an array. Ya just + # gotta chug through every value line by line like that. + + # You also have associative arrays + assoc["foo"] = "bar" + assoc["bar"] = "baz" + + # And multi-dimensional arrays, with some limitations I won't mention here + multidim[0,0] = "foo" + multidim[0,1] = "bar" + multidim[1,0] = "baz" + multidim[1,1] = "boo" + + # You can test for array membership + if ("foo" in assoc) + print "Fooey!" + + # You can also use the 'in' operator to traverse the keys of an array + for (key in assoc) + print assoc[key] + + # The command line is in a special array called ARGV + for (argnum in ARGV) + print ARGV[argnum] + + # You can remove elements of an array + # This is particularly useful to prevent AWK from assuming the arguments + # are files for it to process + delete ARGV[1] + + # The number of command line arguments is in a variable called ARGC + print ARGC + + # AWK has several built-in functions. They fall into three categories. I'll + # demonstrate each of them in their own functions, defined later. + + return_value = arithmetic_functions(a, b, c) + string_functions() + io_functions() +} + +# Here's how you define a function +function arithmetic_functions(a, b, c, localvar) { + + # Probably the most annoying part of AWK is that there are no local + # variables. Everything is global. For short scripts, this is fine, even + # useful, but for longer scripts, this can be a problem. + + # There is a work-around (ahem, hack). Function arguments are local to the + # function, and AWK allows you to define more function arguments than it + # needs. So just stick local variable in the function declaration, like I + # did above. As a convention, stick in some extra whitespace to distinguish + # between actual function parameters and local variables. In this example, + # a, b, and c are actual parameters, while d is merely a local variable. + + # Now, to demonstrate the arithmetic functions + + # Most AWK implementations have some standard trig functions + localvar = sin(a) + localvar = cos(a) + localvar = atan2(a, b) # arc tangent of b / a + + # And logarithmic stuff + localvar = exp(a) + localvar = log(a) + + # Square root + localvar = sqrt(a) + + # Truncate floating point to integer + localvar = int(5.34) # localvar => 5 + + # Random numbers + srand() # Supply a seed as an argument. By default, it uses the time of day + localvar = rand() # Random number between 0 and 1. + + # Here's how to return a value + return localvar +} + +function string_functions( localvar, arr) { + + # AWK, being a string-processing language, has several string-related + # functions, many of which rely heavily on regular expressions. + + # Search and replace, first instance (sub) or all instances (gsub) + # Both return number of matches replaced + localvar = "fooooobar" + sub("fo+", "Meet me at the ", localvar) # localvar => "Meet me at the bar" + gsub("e+", ".", localvar) # localvar => "m..t m. at th. bar" + + # Search for a string that matches a regular expression + # index() does the same thing, but doesn't allow a regular expression + match(localvar, "t") # => 4, since the 't' is the fourth character + + # Split on a delimiter + split("foo-bar-baz", arr, "-") # a => ["foo", "bar", "baz"] + + # Other useful stuff + sprintf("%s %d %d %d", "Testing", 1, 2, 3) # => "Testing 1 2 3" + substr("foobar", 2, 3) # => "oob" + substr("foobar", 4) # => "bar" + length("foo") # => 3 + tolower("FOO") # => "foo" + toupper("foo") # => "FOO" +} + +function io_functions( localvar) { + + # You've already seen print + print "Hello world" + + # There's also printf + printf("%s %d %d %d\n", "Testing", 1, 2, 3) + + # AWK doesn't have file handles, per se. It will automatically open a file + # handle for you when you use something that needs one. The string you used + # for this can be treated as a file handle, for purposes of I/O. This makes + # it feel sort of like shell scripting: + + print "foobar" >"/tmp/foobar.txt" + + # Now the string "/tmp/foobar.txt" is a file handle. You can close it: + close("/tmp/foobar.txt") + + # Here's how you run something in the shell + system("echo foobar") # => prints foobar + + # Reads a line from standard input and stores in localvar + getline localvar + + # Reads a line from a pipe + "echo foobar" | getline localvar # localvar => "foobar" + close("echo foobar") + + # Reads a line from a file and stores in localvar + getline localvar <"/tmp/foobar.txt" + close("/tmp/foobar.txt") +} + +# As I said at the beginning, AWK programs consist of a collection of patterns +# and actions. You've already seen the all-important BEGIN pattern. Other +# patterns are used only if you're processing lines from files or standard +# input. +# +# When you pass arguments to AWK, they are treated as file names to process. +# It will process them all, in order. Think of it like an implicit for loop, +# iterating over the lines in these files. these patterns and actions are like +# switch statements inside the loop. + +/^fo+bar$/ { + + # This action will execute for every line that matches the regular + # expression, /^fo+bar$/, and will be skipped for any line that fails to + # match it. Let's just print the line: + + print + + # Whoa, no argument! That's because print has a default argument: $0. + # $0 is the name of the current line being processed. It is created + # automatically for you. + + # You can probably guess there are other $ variables. Every line is + # implicitely split before every action is called, much like the shell + # does. And, like the shell, each field can be access with a dollar sign + + # This will print the second and fourth fields in the line + print $2, $4 + + # AWK automatically defines many other variables to help you inspect and + # process each line. The most important one is NF + + # Prints the number of fields on this line + print NF + + # Print the last field on this line + print $NF +} + +# Every pattern is actually a true/false test. The regular expression in the +# last pattern is also a true/false test, but part of it was hidden. If you +# don't give it a string to test, it will assume $0, the line that it's +# currently processing. Thus, the complete version of it is this: + +$0 ~ /^fo+bar$/ { + print "Equivalent to the last pattern" +} + +a > 0 { + # This will execute once for each line, as long as a is positive +} + +# You get the idea. Processing text files, reading in a line at a time, and +# doing something with it, particularly splitting on a delimiter, is so common +# in UNIX that AWK is a scripting language that does all of it for you, without +# you needing to ask. All you have to do is write the patterns and actions +# based on what you expect of the input, and what you want to do with it. + +# Here's a quick example of a simple script, the sort of thing AWK is perfect +# for. It will read a name from standard input and then will print the average +# age of everyone with that first name. Let's say you supply as an argument the +# name of a this data file: +# +# Bob Jones 32 +# Jane Doe 22 +# Steve Stevens 83 +# Bob Smith 29 +# Bob Barker 72 +# +# Here's the script: + +BEGIN { + + # First, ask the user for the name + print "What name would you like the average age for?" + + # Get a line from standard input, not from files on the command line + getline name <"/dev/stdin" +} + +# Now, match every line whose first field is the given name +$1 == name { + + # Inside here, we have access to a number of useful variables, already + # pre-loaded for us: + # $0 is the entire line + # $3 is the third field, the age, which is what we're interested in here + # NF is the number of fields, which should be 3 + # NR is the number of records (lines) seen so far + # FILENAME is the name of the file being processed + # FS is the field separator being used, which is " " here + # ...etc. There are plenty more, documented in the man page. + + # Keep track of a running total and how many lines matched + sum += $3 + nlines++ +} + +# Another special pattern is called END. It will run after processing all the +# text files. Unlike BEGIN, it will only run if you've given it input to +# process. It will run after all the files have been read and processed +# according to the rules and actions you've provided. The purpose of it is +# usually to output some kind of final report, or do something with the +# aggregate of the data you've accumulated over the course of the script. + +END { + if (nlines) + print "The average age for " name " is " sum / nlines +} + +``` +Further Reading: + +* [Awk tutorial](http://www.grymoire.com/Unix/Awk.html) +* [Awk man page](https://linux.die.net/man/1/awk) +* [The GNU Awk User's Guide](https://www.gnu.org/software/gawk/manual/gawk.html) GNU Awk is found on most Linux systems. -- cgit v1.2.3 From 0f90bc5e5c5a7eca4d140d00d22add2f0c36c57f Mon Sep 17 00:00:00 2001 From: hugo Date: Sat, 15 Jul 2017 00:40:58 -0700 Subject: awk-es intro --- es-es/awk-es.html.markdown | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) (limited to 'es-es/awk-es.html.markdown') diff --git a/es-es/awk-es.html.markdown b/es-es/awk-es.html.markdown index 7899fcb5..3b93e03d 100644 --- a/es-es/awk-es.html.markdown +++ b/es-es/awk-es.html.markdown @@ -8,17 +8,17 @@ translators: lang: es-es --- -AWK is a standard tool on every POSIX-compliant UNIX system. It's like a -stripped-down Perl, perfect for text-processing tasks and other scripting -needs. It has a C-like syntax, but without semicolons, manual memory -management, or static typing. It excels at text processing. You can call to it -from a shell script, or you can use it as a stand-alone scripting language. - -Why use AWK instead of Perl? Mostly because AWK is part of UNIX. You can always -count on it, whereas Perl's future is in question. AWK is also easier to read -than Perl. For simple text-processing scripts, particularly ones that read -files line by line and split on delimiters, AWK is probably the right tool for -the job. +AWK es una herramienta estándar en cada sistema UNIX compatible con POSIX. +Es como un Perl restringido, perfecto para tareas de procesamiento de texto y +otras necesidades de scripting. Tiene una sintaxis similar a C, pero sin +puntos y comas, manejo manual de memoria y tipado estático. Puedes llamarlo +desde un script de shell o usarlo como un lenguaje stand-alone para scripting. + +¿Por qué elegir AWK sobre Perl? Principalmente, porque AWK es parte de UNIX. +Siempre puedes contar con él, mientras que el futuro de Perl está en duda. AWK +es más fácil de leer que Perl. Para scripts sencillos de procesamiento de texto, +particularmente si es para leer archivos línea a línea y dividir por +delimitadores, probablemente AWK es la herramienta correcta para el trabajo. ```awk #!/usr/bin/awk -f -- cgit v1.2.3 From a276468f2989dbb61eb16428d163c0c4333e25bf Mon Sep 17 00:00:00 2001 From: hugo Date: Sat, 15 Jul 2017 01:16:11 -0700 Subject: awk-es script start --- es-es/awk-es.html.markdown | 45 +++++++++++++++++++++++---------------------- 1 file changed, 23 insertions(+), 22 deletions(-) (limited to 'es-es/awk-es.html.markdown') diff --git a/es-es/awk-es.html.markdown b/es-es/awk-es.html.markdown index 3b93e03d..ef0a975f 100644 --- a/es-es/awk-es.html.markdown +++ b/es-es/awk-es.html.markdown @@ -23,26 +23,27 @@ delimitadores, probablemente AWK es la herramienta correcta para el trabajo. ```awk #!/usr/bin/awk -f -# Comments are like this +# Los comentarios tienen este aspecto. + +# Los programas AWK son una colección de patrones y acciones. El patrón más +# importante es BEGIN. Las acciones van en bloques delimitados por llaves. -# AWK programs consist of a collection of patterns and actions. The most -# important pattern is called BEGIN. Actions go into brace blocks. BEGIN { - # BEGIN will run at the beginning of the program. It's where you put all - # the preliminary set-up code, before you process any text files. If you - # have no text files, then think of BEGIN as the main entry point. + # BEGIN correrá al inicio del programa. Es donde pones todo el código + # preliminar antes de procesar los archivos de texto. Si no tienes archivos + # de texto, piensa en BEGIN como el punto de entrada principal del script. - # Variables are global. Just set them or use them, no need to declare.. + # Las variables son globales. Asígnalas o úsalas sin declararlas. count = 0 - # Operators just like in C and friends + # Los operadores son justo como en C (y amigos). a = count + 1 b = count - 1 c = count * 1 d = count / 1 - e = count % 1 # modulus - f = count ^ 1 # exponentiation + e = count % 1 # módulo + f = count ^ 1 # exponenciación a += 1 b -= 1 @@ -51,36 +52,36 @@ BEGIN { e %= 1 f ^= 1 - # Incrementing and decrementing by one + # Incremento y decremento en uno a++ b-- - # As a prefix operator, it returns the incremented value + # Como un operador prefijo, regresa el valor modificado ++a --b - # Notice, also, no punctuation such as semicolons to terminate statements + # Nota que no hay puntación para terminar las instrucciones - # Control statements + # Instrucciones de control if (count == 0) - print "Starting with count of 0" + print "Iniciando count en 0" else - print "Huh?" + print "Eh?" - # Or you could use the ternary operator - print (count == 0) ? "Starting with count of 0" : "Huh?" + # O puedes usar el operador ternario + print (count == 0) ? "Iniciando count en 0" : "Eh?" - # Blocks consisting of multiple lines use braces + # Bloques formados por múltiples líneas usan llaves while (a < 10) { - print "String concatenation is done" " with a series" " of" - " space-separated strings" + print "La concatenación de strings se hace " " con series " " de" + " strings separados por espacios" print a a++ } for (i = 0; i < 10; i++) - print "Good ol' for loop" + print "El viejo confiable ciclo for" # As for comparisons, they're the standards: a < b # Less than -- cgit v1.2.3 From fed2f2a19e3a5f36c666bc46063dd90f535b311c Mon Sep 17 00:00:00 2001 From: hugo Date: Sat, 15 Jul 2017 01:21:00 -0700 Subject: awk-es script concatenate --- es-es/awk-es.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'es-es/awk-es.html.markdown') diff --git a/es-es/awk-es.html.markdown b/es-es/awk-es.html.markdown index ef0a975f..628bf9ae 100644 --- a/es-es/awk-es.html.markdown +++ b/es-es/awk-es.html.markdown @@ -73,8 +73,8 @@ BEGIN { # Bloques formados por múltiples líneas usan llaves while (a < 10) { - print "La concatenación de strings se hace " " con series " " de" - " strings separados por espacios" + print "La concatenación de strings se hace " " con series " + print " de" " strings separados por espacios" print a a++ -- cgit v1.2.3 From 915a4b21f7f996e2c94e5e2d810e749b2cdaa570 Mon Sep 17 00:00:00 2001 From: hugo Date: Sat, 15 Jul 2017 02:02:03 -0700 Subject: awk-es script trig funcs --- es-es/awk-es.html.markdown | 88 ++++++++++++++++++++++++---------------------- 1 file changed, 45 insertions(+), 43 deletions(-) (limited to 'es-es/awk-es.html.markdown') diff --git a/es-es/awk-es.html.markdown b/es-es/awk-es.html.markdown index 628bf9ae..75b5d946 100644 --- a/es-es/awk-es.html.markdown +++ b/es-es/awk-es.html.markdown @@ -83,19 +83,19 @@ BEGIN { for (i = 0; i < 10; i++) print "El viejo confiable ciclo for" - # As for comparisons, they're the standards: - a < b # Less than - a <= b # Less than or equal - a != b # Not equal - a == b # Equal - a > b # Greater than - a >= b # Greater than or equal - - # Logical operators as well + # Los operaciones de comparación son estándar... + a < b # Menor que + a <= b # Menor o igual que + a != b # No igual + a == b # Igual + a > b # Mayor que + a >= b # Mayor o igual que + + # ...así como los operadores lógicos a && b # AND a || b # OR - # In addition, there's the super useful regular expression match + # Además están las expresiones regulares if ("foo" ~ "^fo+$") print "Fooey!" if ("boo" !~ "^fo+$") @@ -104,83 +104,85 @@ BEGIN { # Arrays arr[0] = "foo" arr[1] = "bar" - # Unfortunately, there is no other way to initialize an array. Ya just - # gotta chug through every value line by line like that. + # Desafortunadamente no hay otra manera de inicializar un array. + # Tienes que inicializar cada posición del array. - # You also have associative arrays + # También hay arrays asociativos assoc["foo"] = "bar" assoc["bar"] = "baz" - # And multi-dimensional arrays, with some limitations I won't mention here + # Y arrays multidimensionales con limitaciones que no mencionaré aquí multidim[0,0] = "foo" multidim[0,1] = "bar" multidim[1,0] = "baz" multidim[1,1] = "boo" - # You can test for array membership + # Puedes probar pertenencia a un array if ("foo" in assoc) print "Fooey!" - # You can also use the 'in' operator to traverse the keys of an array + # También puedes usar el operador 'in' para iterar las claves de un array for (key in assoc) print assoc[key] - # The command line is in a special array called ARGV + # La terminal es un array especial llamado ARGV for (argnum in ARGV) print ARGV[argnum] - # You can remove elements of an array - # This is particularly useful to prevent AWK from assuming the arguments - # are files for it to process + # Puedes eliminar elementos de un array. + # Esto es útil para prevenir que AWK suponga que algunos argumentos + # son archivos por procesar. delete ARGV[1] - # The number of command line arguments is in a variable called ARGC + # El número de argumentos de la terminal está en la variable ARGC print ARGC - # AWK has several built-in functions. They fall into three categories. I'll - # demonstrate each of them in their own functions, defined later. + # AWK tiene tres categorías de funciones incluidas. + # Demostraré esas funciones posteriormente. return_value = arithmetic_functions(a, b, c) string_functions() io_functions() } -# Here's how you define a function +# Así se define una función function arithmetic_functions(a, b, c, localvar) { - # Probably the most annoying part of AWK is that there are no local - # variables. Everything is global. For short scripts, this is fine, even - # useful, but for longer scripts, this can be a problem. + # Probablemente la parte más molesta de AWK es que no hay variables locales + # Todo es global. No es problema en scripts pequeños, pero sí para + # scripts más grandes. - # There is a work-around (ahem, hack). Function arguments are local to the - # function, and AWK allows you to define more function arguments than it - # needs. So just stick local variable in the function declaration, like I - # did above. As a convention, stick in some extra whitespace to distinguish - # between actual function parameters and local variables. In this example, - # a, b, and c are actual parameters, while d is merely a local variable. + # Hay un work-around (mmm... hack). Los argumentos de las funciones son + # locales para la función, y AWK permite definir más argumentos de función + # de los que necesita, por lo que define las variables locales en la + # declaración como en la función de arriba. Como convención, agrega + # espacios en blanco para distinguir los parámetros de la función de las + # variables locales. En este ejemplo, a, b y c son parámetros y localvar es una + # variable local. - # Now, to demonstrate the arithmetic functions + # Ahora, a demostrar las funciones aritméticas - # Most AWK implementations have some standard trig functions + # La mayoría de las implementaciones de AWK tienen funciones + # trigonométricas estándar localvar = sin(a) localvar = cos(a) - localvar = atan2(a, b) # arc tangent of b / a + localvar = atan2(a, b) # arcotangente de b / a - # And logarithmic stuff + # Y cosas logarítmicas localvar = exp(a) localvar = log(a) - # Square root + # Raíz cuadrada localvar = sqrt(a) - # Truncate floating point to integer + # Trucar un flotante a entero localvar = int(5.34) # localvar => 5 - # Random numbers - srand() # Supply a seed as an argument. By default, it uses the time of day - localvar = rand() # Random number between 0 and 1. + # Números aleatorios + srand() # La semilla es el argumento. Por defecto usa el tiempo del sistema + localvar = rand() # Número aleatorio entre 0 y 1. - # Here's how to return a value + # Y aquí se regresa el valor return localvar } -- cgit v1.2.3 From 3d3ab700d17a701e2363047c0c9c54397a99d700 Mon Sep 17 00:00:00 2001 From: hugo Date: Sat, 15 Jul 2017 11:33:24 -0700 Subject: string funcs --- es-es/awk-es.html.markdown | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) (limited to 'es-es/awk-es.html.markdown') diff --git a/es-es/awk-es.html.markdown b/es-es/awk-es.html.markdown index 75b5d946..3e319267 100644 --- a/es-es/awk-es.html.markdown +++ b/es-es/awk-es.html.markdown @@ -188,11 +188,11 @@ function arithmetic_functions(a, b, c, localvar) { function string_functions( localvar, arr) { - # AWK, being a string-processing language, has several string-related - # functions, many of which rely heavily on regular expressions. + # AWK tiene algunas funciones para procesamiento de strings, + # y muchas dependen fuertemente en expresiones regulares. - # Search and replace, first instance (sub) or all instances (gsub) - # Both return number of matches replaced + # Buscar y remplazar, primer instancia (sub) o todas las instancias (gsub) + # Ambas regresan el número de matches remplazados. localvar = "fooooobar" sub("fo+", "Meet me at the ", localvar) # localvar => "Meet me at the bar" gsub("e+", ".", localvar) # localvar => "m..t m. at th. bar" -- cgit v1.2.3 From 1a2d09eb811d23d5c805562c6e910e338e39b0d9 Mon Sep 17 00:00:00 2001 From: hugo Date: Sat, 15 Jul 2017 11:50:55 -0700 Subject: string patterns --- es-es/awk-es.html.markdown | 91 +++++++++++++++++++++++----------------------- 1 file changed, 45 insertions(+), 46 deletions(-) (limited to 'es-es/awk-es.html.markdown') diff --git a/es-es/awk-es.html.markdown b/es-es/awk-es.html.markdown index 3e319267..8a1be9dc 100644 --- a/es-es/awk-es.html.markdown +++ b/es-es/awk-es.html.markdown @@ -197,14 +197,14 @@ function string_functions( localvar, arr) { sub("fo+", "Meet me at the ", localvar) # localvar => "Meet me at the bar" gsub("e+", ".", localvar) # localvar => "m..t m. at th. bar" - # Search for a string that matches a regular expression - # index() does the same thing, but doesn't allow a regular expression - match(localvar, "t") # => 4, since the 't' is the fourth character + # Buscar una cadena que haga match con una expresión regular + # index() hace lo mismo, pero no permite expresiones regulares + match(localvar, "t") # => 4, dado que 't' es el cuarto caracter - # Split on a delimiter + # Separar con base en un delimitador split("foo-bar-baz", arr, "-") # a => ["foo", "bar", "baz"] - # Other useful stuff + # Otras funciones útiles sprintf("%s %d %d %d", "Testing", 1, 2, 3) # => "Testing 1 2 3" substr("foobar", 2, 3) # => "oob" substr("foobar", 4) # => "bar" @@ -215,87 +215,86 @@ function string_functions( localvar, arr) { function io_functions( localvar) { - # You've already seen print + # Ya has visto print print "Hello world" - # There's also printf + # También hay printf printf("%s %d %d %d\n", "Testing", 1, 2, 3) - # AWK doesn't have file handles, per se. It will automatically open a file - # handle for you when you use something that needs one. The string you used - # for this can be treated as a file handle, for purposes of I/O. This makes - # it feel sort of like shell scripting: + # AWK no tiene handles de archivos en sí mismo. Automáticamente abrirá un + # handle de archivo cuando use algo que necesite uno. El string que usaste + # para esto puede ser tratada como un handle de archivo para propósitos de I/O. + # Esto lo hace similar al scripting de shell: print "foobar" >"/tmp/foobar.txt" - # Now the string "/tmp/foobar.txt" is a file handle. You can close it: + # Ahora el string "/tmp/foobar.txt" es un handle. Puedes cerrarlo: close("/tmp/foobar.txt") - # Here's how you run something in the shell - system("echo foobar") # => prints foobar + # Aquí está como correr algo en el shell + system("echo foobar") # => muestra foobar - # Reads a line from standard input and stores in localvar + # Lee una línea de la entrada estándar (stdin) y lo guarda en localvar getline localvar - # Reads a line from a pipe + # Lee una línea desde un pipe "echo foobar" | getline localvar # localvar => "foobar" close("echo foobar") - # Reads a line from a file and stores in localvar + # Lee una línea desde un archivo y la guarda en localvar getline localvar <"/tmp/foobar.txt" close("/tmp/foobar.txt") } -# As I said at the beginning, AWK programs consist of a collection of patterns -# and actions. You've already seen the all-important BEGIN pattern. Other -# patterns are used only if you're processing lines from files or standard -# input. -# -# When you pass arguments to AWK, they are treated as file names to process. -# It will process them all, in order. Think of it like an implicit for loop, -# iterating over the lines in these files. these patterns and actions are like -# switch statements inside the loop. +# Como dije al inicio, los programas en AWK son una colección de patrones y +# acciones. Ya conociste el patrón BEGIN. otros patrones sólo se usan si estás +# procesando líneas desde archivos o stdin. + +# Cuando pasas argumentos a AWK, son tratados como nombres de archivos a +# procesar. Los va a procesar todos, en orden. Imagínalos como un ciclo for +# implícito, iterando sobre las líneas de estos archivos. Estos patrones y +# acciones son como instrucciones switch dentro del ciclo. /^fo+bar$/ { - # This action will execute for every line that matches the regular - # expression, /^fo+bar$/, and will be skipped for any line that fails to - # match it. Let's just print the line: + # Esta acción se ejecutará por cada línea que haga match con la expresión + # regular /^fo+bar$/, y será saltada por cualquier línea que no haga match. + # Vamos a sólo mostrar la línea: print - # Whoa, no argument! That's because print has a default argument: $0. - # $0 is the name of the current line being processed. It is created - # automatically for you. + # ¡Wow, sin argumento! Eso es porque print tiene uno por defecto: $0. + # $0 es el nombre de la línea actual que se está procesando. + # Se crea automáticamente para ti. - # You can probably guess there are other $ variables. Every line is - # implicitely split before every action is called, much like the shell - # does. And, like the shell, each field can be access with a dollar sign + # Probablemente puedas adivinar que hay otras variables $. Cada línea es + # separada implícitamente antes de que se llame cada acción, justo como lo + # hace shell. Y, como shell, cada campo puede ser accesado con $. - # This will print the second and fourth fields in the line + # Esto mostrará el segundo y cuarto campos de la línea print $2, $4 - # AWK automatically defines many other variables to help you inspect and - # process each line. The most important one is NF + # AWK automáticamente define muchas otras variables que te ayudan a + # inspeccionar y procesar cada línea. La más importante es NF - # Prints the number of fields on this line + # Imprime el número de campos de esta línea print NF - # Print the last field on this line + # Imprime el último campo de esta línea print $NF } -# Every pattern is actually a true/false test. The regular expression in the -# last pattern is also a true/false test, but part of it was hidden. If you -# don't give it a string to test, it will assume $0, the line that it's -# currently processing. Thus, the complete version of it is this: +# Cada patrón es realmente un prueba de verdadero/falso. La expresión regular +# en el último patrón también es una prueba verdadero/falso, pero parte de eso +# estaba oculto. Si no le das un string a la prueba, supondrá $0, la línea que +# se está procesando. La versión completa de esto es: $0 ~ /^fo+bar$/ { - print "Equivalent to the last pattern" + print "Equivalente al último patrón" } a > 0 { - # This will execute once for each line, as long as a is positive + # Esto se ejecutará una vez por línea, mientras a sea positivo } # You get the idea. Processing text files, reading in a line at a time, and -- cgit v1.2.3 From bad152cde0ca4561ba7ee0adb1f197139bd76867 Mon Sep 17 00:00:00 2001 From: hugo Date: Sat, 15 Jul 2017 12:08:09 -0700 Subject: example --- es-es/awk-es.html.markdown | 74 +++++++++++++++++++++++----------------------- 1 file changed, 37 insertions(+), 37 deletions(-) (limited to 'es-es/awk-es.html.markdown') diff --git a/es-es/awk-es.html.markdown b/es-es/awk-es.html.markdown index 8a1be9dc..f3d7b841 100644 --- a/es-es/awk-es.html.markdown +++ b/es-es/awk-es.html.markdown @@ -297,16 +297,16 @@ a > 0 { # Esto se ejecutará una vez por línea, mientras a sea positivo } -# You get the idea. Processing text files, reading in a line at a time, and -# doing something with it, particularly splitting on a delimiter, is so common -# in UNIX that AWK is a scripting language that does all of it for you, without -# you needing to ask. All you have to do is write the patterns and actions -# based on what you expect of the input, and what you want to do with it. - -# Here's a quick example of a simple script, the sort of thing AWK is perfect -# for. It will read a name from standard input and then will print the average -# age of everyone with that first name. Let's say you supply as an argument the -# name of a this data file: +# Y ya te das una idea. Procesar archivos de texto, leyendo una línea a la vez, +# y haciendo algo con ella, particularmente separando en un deliminator, es tan +# común en UNIX que AWK es un lenguaje de scripting que hace todo eso por ti +# sin que tengas que pedirlo. Basta con escribir los patrones y acciones +# basados en lo que esperas de la entrada y lo quieras quieras hacer con ella. + +# Aquí está un ejemplo de un script simple, para lo que AWK es perfecto. +# El script lee un nombre de stdin y muestra el promedio de edad para todos los +# que tengan ese nombre. Digamos que como argumento pasamos el nombre de un +# archivo con este contenido: # # Bob Jones 32 # Jane Doe 22 @@ -314,50 +314,50 @@ a > 0 { # Bob Smith 29 # Bob Barker 72 # -# Here's the script: +# Éste es el script: BEGIN { - # First, ask the user for the name - print "What name would you like the average age for?" + # Primero, pedir al usuario el nombre + print "¿Para qué nombre quieres el promedio de edad?" - # Get a line from standard input, not from files on the command line + # Recuperar una línea de stdin, no de archivos en la línea de comandos getline name <"/dev/stdin" } -# Now, match every line whose first field is the given name +# Ahora, hacer match con cada línea cuyo primer campo es el nombre dado $1 == name { - # Inside here, we have access to a number of useful variables, already - # pre-loaded for us: - # $0 is the entire line - # $3 is the third field, the age, which is what we're interested in here - # NF is the number of fields, which should be 3 - # NR is the number of records (lines) seen so far - # FILENAME is the name of the file being processed - # FS is the field separator being used, which is " " here - # ...etc. There are plenty more, documented in the man page. - - # Keep track of a running total and how many lines matched + # Aquí dentro tenemos acceso a variables útiles precargadas: + # $0 es toda la línea + # $3 es el tercer campo, la edad, que es lo que nos interesa + # NF es el número de campos, que debe ser 3 + # NR es el número de registros (líneas) vistos hasta ahora + # FILENAME es el nombre del archivo que está siendo procesado + # FS es el campo separador, " " en este caso + # Y muchas más que puedes conocer ejecutando 'man awk' en la terminal. + + # Llevar el registro de la suma y cuantas líneas han hecho match. sum += $3 nlines++ } -# Another special pattern is called END. It will run after processing all the -# text files. Unlike BEGIN, it will only run if you've given it input to -# process. It will run after all the files have been read and processed -# according to the rules and actions you've provided. The purpose of it is -# usually to output some kind of final report, or do something with the -# aggregate of the data you've accumulated over the course of the script. +# Otro patrón especial es END. Va a ejecutarse después de procesar todos los +# archivos de texto. A diferencia de BEGIN, sólo se ejecuta si le das dado una +# entrada a procesar. Se ejecutará después de que todos los archivos hayan sido +# leídos y procesados según las reglas y acciones que programaste. El propósito +# es usualmente para mostrar un reporte final, o hacer algo con el agregado de +# los datos que has acumulado durante la ejecución del script. END { if (nlines) - print "The average age for " name " is " sum / nlines + print "La edad promedio para " name " es " sum / nlines } ``` -Further Reading: +Más información: -* [Awk tutorial](http://www.grymoire.com/Unix/Awk.html) -* [Awk man page](https://linux.die.net/man/1/awk) -* [The GNU Awk User's Guide](https://www.gnu.org/software/gawk/manual/gawk.html) GNU Awk is found on most Linux systems. +* [Tutorial de AWK](http://www.grymoire.com/Unix/Awk.html) +* [Página man de AWK](https://linux.die.net/man/1/awk) +* [La guía del usuario de GNU Awk](https://www.gnu.org/software/gawk/manual/gawk.html) +GNU Awk se encuentra en la mayoría de los sistemas Linux. -- cgit v1.2.3 From 1bfd17ee7da8bd5e1446b056e266fb4807219505 Mon Sep 17 00:00:00 2001 From: hugo Date: Sat, 15 Jul 2017 12:09:52 -0700 Subject: example 2 --- es-es/awk-es.html.markdown | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) (limited to 'es-es/awk-es.html.markdown') diff --git a/es-es/awk-es.html.markdown b/es-es/awk-es.html.markdown index f3d7b841..307ba817 100644 --- a/es-es/awk-es.html.markdown +++ b/es-es/awk-es.html.markdown @@ -359,5 +359,4 @@ Más información: * [Tutorial de AWK](http://www.grymoire.com/Unix/Awk.html) * [Página man de AWK](https://linux.die.net/man/1/awk) -* [La guía del usuario de GNU Awk](https://www.gnu.org/software/gawk/manual/gawk.html) -GNU Awk se encuentra en la mayoría de los sistemas Linux. +* [La guía del usuario de GNU Awk](https://www.gnu.org/software/gawk/manual/gawk.html): GNU Awk se encuentra en la mayoría de los sistemas Linux. -- cgit v1.2.3