Adler32Checksum
As documented in the [[http://en.wikipedia.org/wiki/Adler-32 | Adler-32 Wikipedia article]]. {{{ awk . . . a,b,len,i,j,MOD_ADLER,MAX_BLOCK) { if (!(sprintf("%c", int(rand()*256)) in ord)) for (i=0; i<256; . . . i++) ord[sprintf("%c",i)]=i # This table initialization should . . . laziness, it's constructive efficiency. } BEGIN {printf "'%X' should match '%s'\n", adler32("Wikipedia"), . . .
4K - last updated 2008-12-31 12:05 UTC by pgas
ArrayLength
Posix does not define a way to get the length of an array, while you could use a loop to count the elements . . . awk #using a counter a[n++]="foo" a[n++]="bar" printf "the length of a is %d\n",n #remember that split . . . returns a value n=split("foo bar",a) printf "the length of a is %d\n",n # loop on the elements . . . you need to pass the length as an extra argument printf "In a function, the length of array is %d\n", . . . } BEGIN{ array[1]="foo";array[2]="bar" printf "the length of array is %d\n", length(array) . . .
2K - last updated 2009-02-09 09:45 UTC by arnold.robbins
awk nawk oawk
in 1977 there was awk.\\ this page attempts to explain the history of awk.\\ the 1978 7th Edition awk(1) . . . \ && (varname != "_print_SYMTAB")) \ printf(fmt, varname, SYMTAB[varname]) > "/dev/stderr"; . . .
2K - last updated 2012-03-18 23:21 UTC by g0pher
AwkDc
This is an awk implementation of the [http://www.gnu.org/software/bc/manual/dc-1.05/html_mono/dc.html|dc] . . . } function _dc_prin(stk) { showop("prin") printf stk[stk[SP]] } function _dc_xprint(stk, tos1, . . . tos1 = _dc_pop(stk) if (_dc_isstr(tos1)) { printf tos1 } else if (_dc_isnum(tos1)) { while (tos1 . . . > 0) { printf "%c", (tos1 - (255 * int(tos1 / 255))) # done . . . = (op + 0) } _dc_put(stk, sig * num) } else { printf "Unhandled op '%s'!\n", op } } # }}} ----- # . . .
12K - last updated 2008-07-17 14:47 UTC by gnomon
AwkFeatureComparison
This page lists which awk implementations support which features. Additions and corrections are very . . . 'BEGIN{a[1]="z";a[2]="a";asort(a);printf "%s %s\n",a[1],a[2]}' # a z}}}| |=FNR|{{{echo . . .
4K - last updated 2015-04-27 13:23 UTC by pgas
AwkGuide
** Work in Progress ** {{{ import from Mark Hobley's wiki }}} <toc> ---- == Overview * [[Overview]] . . . * [[pattern]]s * [[precedence]] * [[print]] * [[printf]] * [[putline]] * [[quotationmark]]s * quotient . . .
4K - last updated 2011-08-14 15:57 UTC by markhobley
AwkOnWindowsHowto
AwkOnWindowsHowto\\ rough cut - needs edit {{{ 3) awk command line switches/usage from a win32 cmd.exe . . . != "SYMTAB") && (varname != "array")) \ printf("SYMTAB[%s]=%s\n", varname, SYMTAB[varname]) . . .
3K - last updated 2010-10-24 07:44 UTC by g0pher
AwkTips
<toc> ---- == Be idiomatic! In this paragraph, we give some hints on how to write more idiomatic . . . results: {{{ # input: 2.5943 10 awk '{$1=sprintf("%d",$1); # truncates decimals, but also explicitly . . . wrong!" } # this is printed }}} Here, after the sprintf(), awk notes that we want $1 to be a string . . . instead WON'T work!), doing "$1=$1+0" after the sprintf(), or using some other means to truncate the . . . to accomplish the task, which exploits the way printf works (many thanks to prince_jammys from #awk . . .
31K - last updated 2009-03-24 16:54 UTC by waldner
case sensitivity
== Indentifier names == The [[awk]] interpreter is lettercase sensitive. This means that [[variable name]]s . . . { dog = "Benjamin" Dog = "Samba" DOG = "Bernie" printf "The three dogs are named %s, %s and %s.\n", . . .
1K - last updated 2011-06-25 05:14 UTC by pgas
Columnate
This script columnates the input file, so that columns line up like in the GNU column(1) command. Its . . . split(line[nr], fields) for (f=1; f<nf; f++) printf "%-*s", max[f]+2, fields[f] print fields[f] . . .
1K - last updated 2009-02-28 21:32 UTC by h-67-101-152-180.nycmny83.dynamic.covad.net
comp.lang.awk FAQ
This material of this faq originates from the comp.lang.awk FAQ that you can find there: * http://www.faqs.org/faqs/computer-lang/awk/faq/ . . . answer]] ---- == How do I have dynamic-width printf strings, like C? <include "PrintfDynamicWidth"> . . . [[http://awk.freeshell.org/?action=edit;id=PrintfDynamicWidth| Edit this answer]] ---- == Why . . .
8K - last updated 2009-03-04 12:42 UTC by pgas
comp.lang.awk FAQJapanese
This material of this faq originates from the comp.lang.awk FAQ that you can find there: * http://www.faqs.org/faqs/computer-lang/awk/faq/ . . . answer]] ---- == How do I have dynamic-width printf strings, like C? <include "PrintfDynamicWidthJapanese"> . . . [[http://awk.freeshell.org/?action=edit;id=PrintfDynamicWidthJapanese| Edit this answer]] . . .
4K - last updated 2008-11-24 09:01 UTC by pgas
ConvertHexToFloatingPoint
This code uses [[gawkism|gawk specific features]], such as the [[http://www.gnu.org/manual/gawk/html_node/Strtonum-Function.html][strtonum]] . . . { p=(char *)&f[j]; for(int i=0;i<4;i++) printf("%02x ",(*(p+i)&0xFF)); printf("%.3f\n",f[j]); . . . return fval } BEGIN { x = f_ieee754(0x41f24000) printf("x = %f\n",x) } you should get 30.28125 . . .
3K - last updated 2010-06-23 19:49 UTC by john b
DeleteTrailingNewlines
Simple oneliner that deletes the trailing newlines of a file: {{{ sh awk '!NF{b=b "\n";next} {printf . . . add one ;): {{{ sh awk '!NF{b=b "\n";next} {printf "%s%s",b,$0;b="\n"} END {print "\n"}' file }}} . . .
1K - last updated 2008-12-31 12:07 UTC by pgas
ENVIRON
Modern versions of new awk (gawk, mawk, Bell Labs awk, any POSIX awk) all provide an array named ENVIRON. . . . use a simple loop: {{{ awk for (i in ENVIRON) printf("ENVIRON['%s'] = '%s'\n", i, ENVIRON[i]) }}} . . .
1K - last updated 2008-11-19 13:13 UTC by pgas
ENVIRONJapanese
Modern versions of new awk (gawk, mawk, Bell Labs awk, any POSIX awk) all provide an array named ENVIRON. . . . use a simple loop: {{{ awk for (i in ENVIRON) printf("ENVIRON['%s'] = '%s'\n", i, ENVIRON[i]) }}} . . .
1K - last updated 2008-11-24 08:05 UTC by pgas
FileAndBitJoinClone
== Problem Description This was difficult to hash out. Eventually the task was described as, "for each . . . < FILE) > 0) print (($3 in BL) ? BL[$3] : sprintf(ERRSTR, $3, BIT, FILE, $1)) close(FILE) # equivalently . . .
7K - last updated 2009-03-08 16:26 UTC by waldner
FIXES
[[FIXES]] revised: . . . a filename (p 63).\\ added some missing ansi printf conversion letters: %i %X %E %G.\\ no . . . causes immediate advance to next input file.\\ printf("%c", 0) to include a null byte in output.\\ . . .
6K - last updated 2014-01-15 23:17 UTC by g0ph3r
FormatFileSizes
From time to time people ask how to sort the output of {{{du -h}}}. This is not particularly easy, since . . . for (i=3;i>=0;--i) { if ( size > 1024 ^i) {printf "%.2f%s\t%s\n",(size / 1024^i),u[i],name;next}}}' . . .
1K - last updated 2008-11-29 05:22 UTC by gnomon
GeneralizedTextReplacement
Some times people need to recode in awk something they were previously doing with sed or another tool. . . . # prepend/append other text # rep[i] = sprintf("%05d", mtch[i]*4) # arithmetic (like perl) . . .
6K - last updated 2009-03-26 20:38 UTC by waldner
GeoLocation
{{{ awk #!/bin/gawk -f function getcoord(string, a) { split(string, a, ":") gsub(/\"/, "", a[2]) return . . . socket = "/inet/tcp/0/" host "/80" printf "GET / HTTP/1.1\r\nHost: %s\n\n", host |& . . . socket for (header in headers) { printf "%s\r\n", headers[header] |& socket } printf . . . = getcoord(coords[3]) lon = getcoord(coords[4]) printf "http://maps.google.com/maps?q=%s,%s\n", lat, . . .
1K - last updated 2011-11-14 16:35 UTC by pgas
LargestAccurateNumber
Most [[awk]] implementations use floating point double precision to represent every kind of numeric value. . . . {{{ sh awk 'BEGIN{for (i = 0; i < 64; i++) printf "%s\t%19.0f\t%s\n", i, 2^i, (((2^i+1) == (2^i))? . . .
3K - last updated 2013-04-12 14:52 UTC by ttmrichter
LevenshteinEditDistance
The [http://en.wikipedia.org/wiki/Levenshtein_distance|Levenshtein edit distance] calculation is useful . . . levdist(str1, str2) if (testval == correctval) { printf "%s:\tCorrect distance between '%s' and '%s'\n", . . .
6K - last updated 2010-04-16 10:19 UTC by pgas
LshalOutputParser
=== Problem Specification 10:50 <Thanatermesis> i want to obtain the model of the disk, for example, . . . = 1 inBlock = 0 FS = " = " } function die(msg) { printf "ERROR on line %d of input: %s\n", NR, msg >> . . . info } else { type = "udi" val = trim($2) } #printf "!%s! ---- !%s! ---- !%s!\n", key, val, type . . . \ length(PROPERTIES["storage.model"]) > 2) { printf "device:\t%s\nmodel:\t%s\n", PROPERTIES["block.storage_device"], . . .
3K - last updated 2008-06-27 16:22 UTC by gnomon
MayorNumeroPreciso-español
La mayoría de las implementaciones usan números de coma flotante de alta precisión conocidos como "double" . . . N+1: {{{ awk 'BEGIN{for (i = 0; i < 64; i++) printf "%s\t%19.0f\t%s\n", i, 2^i, (((2^i+1) == (2^i))? . . .
1K - last updated 2009-01-03 07:01 UTC by fcr
MostrarApostrofos-español
Esta pregunta es tan frecuente que merece su propia respuesta. Y aunque pareciera que esto es una limitación . . . la secuencia de escape en base ocho ('\047') o printf ('print "%c", 39'). No use las secuencias de . . . "\047foo!\047"}' }}} ==== Usos y abusos de printf O simplemente podríamos usar printf: {{{ awk . . . 'BEGIN{printf "%cfoo!%c\n", 39, 39}' }}} ...pero entonces . . . extensión de printf]] que . . .
4K - last updated 2009-01-15 20:03 UTC by fcr
Newline
"print" prints a newline by default. If you don't want a newline, you can use printf instead it is straightforward, . . . string and avoid putting data in it. {{{ awk printf "%s",$0 #prints the record without adding a . . . you can do something like: {{{ sh awk '{printf "%s%s",separator,$0;separator="|"}END{printf . . . also change ORS to "remove" the newlines {{{ sh printf "%s\n" foo bar | awk -v ORS="|" '{print $0}' . . .
1K - last updated 2011-07-05 10:53 UTC by pgas
oawk
oawk is "old awk", it is the default /usr/bin/awk on Solaris and should not be used. You can also find . . . parsing (here thinks "<bar>" is arg to sprintf()): {{{sh $ echo "foo" | /usr/xpg4/bin/awk '{print . . . sprintf("%s =",$0), "<bar>"}' foo = <bar> . . . $ echo "foo" | /usr/bin/awk '{print sprintf("%s =",$0), "<bar>"}' foo = }}} ==== no . . .
5K - last updated 2012-01-24 08:29 UTC by pgas
PassingVariablesToTheParentProcess
How can I put values into the environment of the program that called my awk program? Short answer, you . . . after running the awk program: {{{ awk 'BEGIN { printf("NEWVAR='%s'\n", somevalue) }' > /tmp/awk.$$ . . .
1K - last updated 2008-11-19 07:45 UTC by pgas
PassingVariablesToTheParentProcessJapanese
How can I put values into the environment of the program that called my awk program? Short answer, you . . . after running the awk program: {{{ awk 'BEGIN { printf("NEWVAR='%s'\n", somevalue) }' > /tmp/awk.$$ . . .
1K - last updated 2008-11-24 08:05 UTC by pgas
PreguntasFrecuentes
<toc> ---- == ¿Cómo muestro un rango de campos? Desde [[RangoDeCampos-español]], [[http://awk.freeshell.org/es?action=edit;id=RangoDeCampos-espa%C3%B1ol| . . . ---- == ¿Cómo usar printf? Desde [[printf-español]], [[http://awk.freeshell.org/es?action=edit;id=printf-espa%C3%B1ol|editar]]: . . . <include "printf-español"> ---- == ¿Cómo encontrar el mayor . . .
2K - last updated 2009-01-03 03:01 UTC by fcr
PrimeNumberSieve
This is the standard sieve of Eratosthenes implemented in portable awk. The running time of the bare . . . primes) } #for (i = 0; i in primes; i++) printf "%2s: %3d\n", i, primes[i] } }}} === Methodology . . .
4K - last updated 2008-06-19 05:56 UTC by gnomon
PrintASingleQuote
This question gets asked often enough that it deserves its own answer. This common question doesn't actually . . . Story Use octal [[escape sequence]]s ('\047') or printf ('printf "%c", 39'). Do not use hex escape sequences . . . "\047foo!\047"}' }}} ==== Uses and Abuses of printf Or we could use printf: {{{ awk 'BEGIN{printf . . . printf extension]] for re-using . . . printf arguments according to a position specified . . .
5K - last updated 2015-07-05 09:45 UTC by pitman
PrintASingleQuoteJapanese
This page is the translated page of PrintASingleQuote written in Japanese. この問題は何度も質問される内容なので、議論するのに値する問題です。 . . . === 小話 8 進数のエスケープシーケンス ('\047') または printf ('printf "%c", 39') を用いてください。 16 進数のエスケープシーケンス . . . {{{ awk 'BEGIN{print "\047foo!\047"}' }}} === printf を酷使せよ もしくは printf を使うこともできます。 {{{ awk 'BEGIN{printf . . . gawk は文字列シーケンスの中の特定の位置によって printf の引数が再利用されるという特徴 [[http://www.gnu.org/software/gawk/manual/html_node/Printf-Ordering.html|a . . . printf extension]] があります・・・。 {{{ awk 'BEGIN{printf . . .
3K - last updated 2008-10-15 14:22 UTC by hi saito
printf-español
Muestra todas las palabras en cada línea: {{{ awk '{for(i=1;i<=NF;++i) printf "%s ", $i;print ""}' . . . en cada línea: {{{ awk '{for(i=2;i<=NF;++i) printf "%s ", $i;print ""}' nombredearchivo }}} Muestra . . . start=3 -v end=5 '{ for(i=start;i<=end;i++) printf "%s ", $i;print "" }' nombredearchivo }}} Muestra . . . en cada línea: {{{ awk '{ i=0; while(++i<8) printf("%s ", $i); print $i }' nombredearchivo }}} . . . los saltos de línea en un archivo: {{{ awk '{ printf "%s ", $O }' nombredearchivo }}} Muestra todo . . .
1K - last updated 2009-01-03 02:53 UTC by fcr
printf
== Usage == === printf [ FORMAT, LIST ] === The **printf** [[variadic]] function provides generic [[string . . . [[standard output]] in a similar manner to the printf function used in the C programming language. . . . The printf function uses the same string formatting functions . . . as [[sprintf]], but printf does not automatically append . . . or [[newline]] character to its output. The printf function provides support for the complete set . . .
2K - last updated 2011-06-09 20:34 UTC by markhobley
PrintfDynamicWidth
With modern awks, you can just do it like you would in C (though the justification is less clear; C doesn't . . . maxlen=length(arr[i]) for (i in arr) printf("%-*s %s\n",maxlen,arr[i],i) }}} With old awks, . . . (maxlen<length(arr[i])) maxlen=length(arr[i]) printfstring="%-" maxlen "s %s\n"; for (i in arr) printf(printfstring,arr[i],i) . . .
1K - last updated 2008-11-24 08:26 UTC by pgas
PrintfDynamicWidthJapanese
With modern awks, you can just do it like you would in C (though the justification is less clear; C doesn't . . . maxlen=length(arr[i]) for (i in arr) printf("%-*s %s\n",maxlen,arr[i],i) }}} With old awks, . . . (maxlen<length(arr[i])) maxlen=length(arr[i]) printfstring="%-" maxlen "s %s\n"; for (i in arr) printf(printfstring,arr[i],i) . . .
1K - last updated 2008-11-24 08:36 UTC by pgas
PrintingNumbers
Use printf and a format string instead of print, some examples: {{{ awk BEGIN { printf "%f", 1000001.10 . . . #prints 1000001.100000 printf "%.3f", 1000001.10 #prints 1000001.100 printf . . . } }}} For more information about printf see [[http://www.gnu.org/software/gawk/manual/html_node/Printf.html#Printf|the . . . in the first place? awk does something like printf using the format string in the variable OFMT, . . . as a string without conversion 12.1231 # same as printf "%.6g",$1 ($1+0 is a number) 12.123 # same as . . .
2K - last updated 2009-03-04 12:34 UTC by pgas
PureEvil
Not related to awk, just for fun. Some deliberately obfuscated and evil commands: {{{ sh # squeeze the . . . one (like tr -s '\n'), assumes a bourne shell printf "%s\n" foo '' '' bar | awk $$${$+ RS=} #another . . .
1K - last updated 2011-09-08 14:00 UTC by pgas
qse
Not a standalone awk, but an interesting library embedding an awk interpreter, from [[https://groups.google.com/group/comp.lang.awk/browse_thread/thread/b02c0d75e49eab75/54fc2c6316d657bc?lnk=gst&q=c%2B%2B+embed#54fc2c6316d657bc| . . . #define FAIL(msg) do { qse_printf(QSE_T("ERR: %s\n"),msg); goto oops; } while(0) . . .
4K - last updated 2011-10-27 06:25 UTC by pgas
RangeOfFields
Printing a range of fields - all fields but the first, for examples, or fields 3 through 8 - is a surprisingly . . . {{{ bash awk '{sep="";for (i=2;i<=NF;i++) {printf "%s%s",sep, $i;sep=" "}; printf "\n"}' file . . . avoids using sep awk '{for (i=2;i<=NF;i++) {printf "%s%s",(i>2?" ":""), $i}; printf "\n"}' file . . . uses OFS and ORS awk '{for (i=2; i<=NF; i++) printf("%s%s", $i, i==NF ? ORS : OFS)}' file }}} A . . . fs_regex, delim) for (i = 3; i <= NF; ++i) printf "%s%s", fld[i], ((i < NF) ? delim[i] : "\n") . . .
10K - last updated 2015-09-08 09:52 UTC by pgas
ReadDirectory
Getting a list of files in a directory is a tricky process. One might be tempted to try use ls and getline, . . . BEGIN { RS = "/" cmd = "cd \""dir"\" && printf '%s/' *" while (cmd | getline > 0) if ($0) . . . files[n++] = $0 close(cmd) for (f in files) printf("/%s/\n", files[f]) } }}} Assuming that dir . . . { RS = "\0\0" cmd = "cd \""dir"\" && printf '%s\\0' *" cmd | getline close(cmd) patsplit($0, . . . files, "[^\0]+") for (f in files) printf("/%s/\n", files[f]) } }}} Here we can read in . . .
2K - last updated 2013-10-03 22:35 UTC by emg
Recursively Include C headers
=== Problem Specification i want to generate one big .hpp file out of multiple .hpp files and want to . . . if (p !~ /\/$/) p = p "/" p = p file if (system(sprintf("/usr/bin/test -f \"%s\"", p)) == 0) return . . . p } printf("error:%s: file not found in include_path\n", . . .
1K - last updated 2011-12-11 05:33 UTC by pgas
RepeatAString
Sometimes it is useful to have something like Perl's 'x' operator, which repeats a string N times. This . . . linear, very compacted, ones based on using {{{printf()}}} and {{{gsub()}}}), but tests showed them . . .
1K - last updated 2009-03-01 19:15 UTC by h-67-101-152-180.nycmny83.dynamic.covad.net
ReverseMapping
{{{ awk # reverse mapping of keys -> values in given array function reverse_mapping(array, tmp_key, . . . 1 a[1] = "a" a[2] = "b" a[3] = "c" for (k in a) printf("a[%s] = %s\n", k, a[k]) reverse_mapping(a) . . . printf("\n") for (k in a) printf("a[%s] = %s\n", k, . . .
2K - last updated 2014-04-23 00:33 UTC by emg
Shellquote
This function ensures that strings you use as arguments to the **system()** function (or **"cmd"{{{|}}}getline** . . . { gsub(/'/, "'\\''", str) return sprintf("'%s'", str) } }}} . . .
1K - last updated 2009-03-01 00:35 UTC by h-67-101-152-180.nycmny83.dynamic.covad.net
ShellQuoting
Quoting can be such a headache for the novice, in shell programming, and especially in awk. Art Povelones . . . "Never say can"q"t."; exit }' awk 'BEGIN { q=sprintf("%c",39); print "Never say can"q"t."; exit }' . . . awk 'BEGIN { q=sprintf("%c",39); print "Never say \"can"q"t.\""; exit . . .
2K - last updated 2008-11-19 07:41 UTC by pgas
ShellQuotingJapanese
シェルプログラミングの引用符、特に awk での引用符は初心者にとっては頭痛の種です。 Art Povelones は 1999 年 9 月 30 日にシェルでの引用符について長編のチュートリアルを投稿してくれました。これは非常に詳細過ぎるため . . . "Never say can"q"t."; exit }' awk 'BEGIN { q=sprintf("%c",39); print "Never say can"q"t."; exit }' . . . awk 'BEGIN { q=sprintf("%c",39); print "Never say \"can"q"t.\""; exit . . .
2K - last updated 2008-11-22 11:16 UTC by 218.231.238.51.eo.eaccess.ne.jp
string manipulation function
The [[awk]] programming language provides a set of [[builtin]] functions for performing various string . . . * [[length]] * [[match]] * [[split]] * [[sprintf]] * [[sub]] * [[substr]] * [[case conversion|tolower]] . . .
1K - last updated 2011-06-07 00:35 UTC by markhobley
text.2.wiki.awk
#: C:\#\awk\lib\text.2.wiki.awk\\ . . . printf("%s", s) | c;\\ . . .
11K - last updated 2012-09-24 14:55 UTC by g0ph3r
tracert.awk
{{{ awk #:: C:\_\_u\tracert.awk #: 2014-07-06 19:47:02 #:: rod.t_2014 #:: extract basename for tracert . . . END { t = "\n\tPress Enter key to continue:\t"; printf("\n\t%s%s", _dt(), t) > _con; getline < . . .
4K - last updated 2014-07-07 06:15 UTC by 212.205.56.222
variable
A '''variable''' is a symbolic name associated with a [[value]]. A variable acts as a container and the . . . { dog = "Benjamin" Dog = "Samba" DOG = "Bernie" printf "The three dogs are named %s, %s and %s.\n", . . .
3K - last updated 2012-04-22 11:42 UTC by unregistered
WartAndWishList
Awk is a wonderful language! That said, there are a few annoying bits... == The Good * well-documented . . . specific escape sequences for strftime and [s]printf) == The Bad * It's quite difficult to map back . . .
7K - last updated 2009-04-13 18:39 UTC by goedel
54 pages found.