Advertisement
opexxx

awk1line.txt

Nov 5th, 2013
305
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 11.32 KB | None | 0 0
  1. HANDY ONE-LINE SCRIPTS FOR AWK 30 April 2008
  2. Compiled by Eric Pement - eric [at] pement.org version 0.27
  3.  
  4. Latest version of this file (in English) is usually at:
  5. http://www.pement.org/awk/awk1line.txt
  6.  
  7. This file will also be available in other languages:
  8. Chinese - http://ximix.org/translation/awk1line_zh-CN.txt
  9.  
  10. USAGE:
  11.  
  12. Unix: awk '/pattern/ {print "$1"}' # standard Unix shells
  13. DOS/Win: awk '/pattern/ {print "$1"}' # compiled with DJGPP, Cygwin
  14. awk "/pattern/ {print \"$1\"}" # GnuWin32, UnxUtils, Mingw
  15.  
  16. Note that the DJGPP compilation (for DOS or Windows-32) permits an awk
  17. script to follow Unix quoting syntax '/like/ {"this"}'. HOWEVER, if the
  18. command interpreter is CMD.EXE or COMMAND.COM, single quotes will not
  19. protect the redirection arrows (<, >) nor do they protect pipes (|).
  20. These are special symbols which require "double quotes" to protect them
  21. from interpretation as operating system directives. If the command
  22. interpreter is bash, ksh or another Unix shell, then single and double
  23. quotes will follow the standard Unix usage.
  24.  
  25. Users of MS-DOS or Microsoft Windows must remember that the percent
  26. sign (%) is used to indicate environment variables, so this symbol must
  27. be doubled (%%) to yield a single percent sign visible to awk.
  28.  
  29. If a script will not need to be quoted in Unix, DOS, or CMD, then I
  30. normally omit the quote marks. If an example is peculiar to GNU awk,
  31. the command 'gawk' will be used. Please notify me if you find errors or
  32. new commands to add to this list (total length under 65 characters). I
  33. usually try to put the shortest script first. To conserve space, I
  34. normally use '1' instead of '{print}' to print each line. Either one
  35. will work.
  36.  
  37. FILE SPACING:
  38.  
  39. # double space a file
  40. awk '1;{print ""}'
  41. awk 'BEGIN{ORS="\n\n"};1'
  42.  
  43. # double space a file which already has blank lines in it. Output file
  44. # should contain no more than one blank line between lines of text.
  45. # NOTE: On Unix systems, DOS lines which have only CRLF (\r\n) are
  46. # often treated as non-blank, and thus 'NF' alone will return TRUE.
  47. awk 'NF{print $0 "\n"}'
  48.  
  49. # triple space a file
  50. awk '1;{print "\n"}'
  51.  
  52. NUMBERING AND CALCULATIONS:
  53.  
  54. # precede each line by its line number FOR THAT FILE (left alignment).
  55. # Using a tab (\t) instead of space will preserve margins.
  56. awk '{print FNR "\t" $0}' files*
  57.  
  58. # precede each line by its line number FOR ALL FILES TOGETHER, with tab.
  59. awk '{print NR "\t" $0}' files*
  60.  
  61. # number each line of a file (number on left, right-aligned)
  62. # Double the percent signs if typing from the DOS command prompt.
  63. awk '{printf("%5d : %s\n", NR,$0)}'
  64.  
  65. # number each line of file, but only print numbers if line is not blank
  66. # Remember caveats about Unix treatment of \r (mentioned above)
  67. awk 'NF{$0=++a " :" $0};1'
  68. awk '{print (NF? ++a " :" :"") $0}'
  69.  
  70. # count lines (emulates "wc -l")
  71. awk 'END{print NR}'
  72.  
  73. # print the sums of the fields of every line
  74. awk '{s=0; for (i=1; i<=NF; i++) s=s+$i; print s}'
  75.  
  76. # add all fields in all lines and print the sum
  77. awk '{for (i=1; i<=NF; i++) s=s+$i}; END{print s}'
  78.  
  79. # print every line after replacing each field with its absolute value
  80. awk '{for (i=1; i<=NF; i++) if ($i < 0) $i = -$i; print }'
  81. awk '{for (i=1; i<=NF; i++) $i = ($i < 0) ? -$i : $i; print }'
  82.  
  83. # print the total number of fields ("words") in all lines
  84. awk '{ total = total + NF }; END {print total}' file
  85.  
  86. # print the total number of lines that contain "Beth"
  87. awk '/Beth/{n++}; END {print n+0}' file
  88.  
  89. # print the largest first field and the line that contains it
  90. # Intended for finding the longest string in field #1
  91. awk '$1 > max {max=$1; maxline=$0}; END{ print max, maxline}'
  92.  
  93. # print the number of fields in each line, followed by the line
  94. awk '{ print NF ":" $0 } '
  95.  
  96. # print the last field of each line
  97. awk '{ print $NF }'
  98.  
  99. # print the last field of the last line
  100. awk '{ field = $NF }; END{ print field }'
  101.  
  102. # print every line with more than 4 fields
  103. awk 'NF > 4'
  104.  
  105. # print every line where the value of the last field is > 4
  106. awk '$NF > 4'
  107.  
  108. STRING CREATION:
  109.  
  110. # create a string of a specific length (e.g., generate 513 spaces)
  111. awk 'BEGIN{while (a++<513) s=s " "; print s}'
  112.  
  113. # insert a string of specific length at a certain character position
  114. # Example: insert 49 spaces after column #6 of each input line.
  115. gawk --re-interval 'BEGIN{while(a++<49)s=s " "};{sub(/^.{6}/,"&" s)};1'
  116.  
  117. ARRAY CREATION:
  118.  
  119. # These next 2 entries are not one-line scripts, but the technique
  120. # is so handy that it merits inclusion here.
  121.  
  122. # create an array named "month", indexed by numbers, so that month[1]
  123. # is 'Jan', month[2] is 'Feb', month[3] is 'Mar' and so on.
  124. split("Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec", month, " ")
  125.  
  126. # create an array named "mdigit", indexed by strings, so that
  127. # mdigit["Jan"] is 1, mdigit["Feb"] is 2, etc. Requires "month" array
  128. for (i=1; i<=12; i++) mdigit[month[i]] = i
  129.  
  130. TEXT CONVERSION AND SUBSTITUTION:
  131.  
  132. # IN UNIX ENVIRONMENT: convert DOS newlines (CR/LF) to Unix format
  133. awk '{sub(/\r$/,"")};1' # assumes EACH line ends with Ctrl-M
  134.  
  135. # IN UNIX ENVIRONMENT: convert Unix newlines (LF) to DOS format
  136. awk '{sub(/$/,"\r")};1'
  137.  
  138. # IN DOS ENVIRONMENT: convert Unix newlines (LF) to DOS format
  139. awk 1
  140.  
  141. # IN DOS ENVIRONMENT: convert DOS newlines (CR/LF) to Unix format
  142. # Cannot be done with DOS versions of awk, other than gawk:
  143. gawk -v BINMODE="w" '1' infile >outfile
  144.  
  145. # Use "tr" instead.
  146. tr -d \r <infile >outfile # GNU tr version 1.22 or higher
  147.  
  148. # delete leading whitespace (spaces, tabs) from front of each line
  149. # aligns all text flush left
  150. awk '{sub(/^[ \t]+/, "")};1'
  151.  
  152. # delete trailing whitespace (spaces, tabs) from end of each line
  153. awk '{sub(/[ \t]+$/, "")};1'
  154.  
  155. # delete BOTH leading and trailing whitespace from each line
  156. awk '{gsub(/^[ \t]+|[ \t]+$/,"")};1'
  157. awk '{$1=$1};1' # also removes extra space between fields
  158.  
  159. # insert 5 blank spaces at beginning of each line (make page offset)
  160. awk '{sub(/^/, " ")};1'
  161.  
  162. # align all text flush right on a 79-column width
  163. awk '{printf "%79s\n", $0}' file*
  164.  
  165. # center all text on a 79-character width
  166. awk '{l=length();s=int((79-l)/2); printf "%"(s+l)"s\n",$0}' file*
  167.  
  168. # substitute (find and replace) "foo" with "bar" on each line
  169. awk '{sub(/foo/,"bar")}; 1' # replace only 1st instance
  170. gawk '{$0=gensub(/foo/,"bar",4)}; 1' # replace only 4th instance
  171. awk '{gsub(/foo/,"bar")}; 1' # replace ALL instances in a line
  172.  
  173. # substitute "foo" with "bar" ONLY for lines which contain "baz"
  174. awk '/baz/{gsub(/foo/, "bar")}; 1'
  175.  
  176. # substitute "foo" with "bar" EXCEPT for lines which contain "baz"
  177. awk '!/baz/{gsub(/foo/, "bar")}; 1'
  178.  
  179. # change "scarlet" or "ruby" or "puce" to "red"
  180. awk '{gsub(/scarlet|ruby|puce/, "red")}; 1'
  181.  
  182. # reverse order of lines (emulates "tac")
  183. awk '{a[i++]=$0} END {for (j=i-1; j>=0;) print a[j--] }' file*
  184.  
  185. # if a line ends with a backslash, append the next line to it (fails if
  186. # there are multiple lines ending with backslash...)
  187. awk '/\\$/ {sub(/\\$/,""); getline t; print $0 t; next}; 1' file*
  188.  
  189. # print and sort the login names of all users
  190. awk -F ":" '{print $1 | "sort" }' /etc/passwd
  191.  
  192. # print the first 2 fields, in opposite order, of every line
  193. awk '{print $2, $1}' file
  194.  
  195. # switch the first 2 fields of every line
  196. awk '{temp = $1; $1 = $2; $2 = temp}' file
  197.  
  198. # print every line, deleting the second field of that line
  199. awk '{ $2 = ""; print }'
  200.  
  201. # print in reverse order the fields of every line
  202. awk '{for (i=NF; i>0; i--) printf("%s ",$i);print ""}' file
  203.  
  204. # concatenate every 5 lines of input, using a comma separator
  205. # between fields
  206. awk 'ORS=NR%5?",":"\n"' file
  207.  
  208. SELECTIVE PRINTING OF CERTAIN LINES:
  209.  
  210. # print first 10 lines of file (emulates behavior of "head")
  211. awk 'NR < 11'
  212.  
  213. # print first line of file (emulates "head -1")
  214. awk 'NR>1{exit};1'
  215.  
  216. # print the last 2 lines of a file (emulates "tail -2")
  217. awk '{y=x "\n" $0; x=$0};END{print y}'
  218.  
  219. # print the last line of a file (emulates "tail -1")
  220. awk 'END{print}'
  221.  
  222. # print only lines which match regular expression (emulates "grep")
  223. awk '/regex/'
  224.  
  225. # print only lines which do NOT match regex (emulates "grep -v")
  226. awk '!/regex/'
  227.  
  228. # print any line where field #5 is equal to "abc123"
  229. awk '$5 == "abc123"'
  230.  
  231. # print only those lines where field #5 is NOT equal to "abc123"
  232. # This will also print lines which have less than 5 fields.
  233. awk '$5 != "abc123"'
  234. awk '!($5 == "abc123")'
  235.  
  236. # matching a field against a regular expression
  237. awk '$7 ~ /^[a-f]/' # print line if field #7 matches regex
  238. awk '$7 !~ /^[a-f]/' # print line if field #7 does NOT match regex
  239.  
  240. # print the line immediately before a regex, but not the line
  241. # containing the regex
  242. awk '/regex/{print x};{x=$0}'
  243. awk '/regex/{print (NR==1 ? "match on line 1" : x)};{x=$0}'
  244.  
  245. # print the line immediately after a regex, but not the line
  246. # containing the regex
  247. awk '/regex/{getline;print}'
  248.  
  249. # grep for AAA and BBB and CCC (in any order on the same line)
  250. awk '/AAA/ && /BBB/ && /CCC/'
  251.  
  252. # grep for AAA and BBB and CCC (in that order)
  253. awk '/AAA.*BBB.*CCC/'
  254.  
  255. # print only lines of 65 characters or longer
  256. awk 'length > 64'
  257.  
  258. # print only lines of less than 65 characters
  259. awk 'length < 64'
  260.  
  261. # print section of file from regular expression to end of file
  262. awk '/regex/,0'
  263. awk '/regex/,EOF'
  264.  
  265. # print section of file based on line numbers (lines 8-12, inclusive)
  266. awk 'NR==8,NR==12'
  267.  
  268. # print line number 52
  269. awk 'NR==52'
  270. awk 'NR==52 {print;exit}' # more efficient on large files
  271.  
  272. # print section of file between two regular expressions (inclusive)
  273. awk '/Iowa/,/Montana/' # case sensitive
  274.  
  275. SELECTIVE DELETION OF CERTAIN LINES:
  276.  
  277. # delete ALL blank lines from a file (same as "grep '.' ")
  278. awk NF
  279. awk '/./'
  280.  
  281. # remove duplicate, consecutive lines (emulates "uniq")
  282. awk 'a !~ $0; {a=$0}'
  283.  
  284. # remove duplicate, nonconsecutive lines
  285. awk '!a[$0]++' # most concise script
  286. awk '!($0 in a){a[$0];print}' # most efficient script
  287.  
  288. CREDITS AND THANKS:
  289.  
  290. Special thanks to the late Peter S. Tillier (U.K.) for helping me with
  291. the first release of this FAQ file, and to Daniel Jana, Yisu Dong, and
  292. others for their suggestions and corrections.
  293.  
  294. For additional syntax instructions, including the way to apply editing
  295. commands from a disk file instead of the command line, consult:
  296.  
  297. "sed & awk, 2nd Edition," by Dale Dougherty and Arnold Robbins
  298. (O'Reilly, 1997)
  299.  
  300. "UNIX Text Processing," by Dale Dougherty and Tim O'Reilly (Hayden
  301. Books, 1987)
  302.  
  303. "GAWK: Effective awk Programming," 3d edition, by Arnold D. Robbins
  304. (O'Reilly, 2003) or at http://www.gnu.org/software/gawk/manual/
  305.  
  306. To fully exploit the power of awk, one must understand "regular
  307. expressions." For detailed discussion of regular expressions, see
  308. "Mastering Regular Expressions, 3d edition" by Jeffrey Friedl (O'Reilly,
  309. 2006).
  310.  
  311. The info and manual ("man") pages on Unix systems may be helpful (try
  312. "man awk", "man nawk", "man gawk", "man regexp", or the section on
  313. regular expressions in "man ed").
  314.  
  315. USE OF '\t' IN awk SCRIPTS: For clarity in documentation, I have used
  316. '\t' to indicate a tab character (0x09) in the scripts. All versions of
  317. awk should recognize this abbreviation.
  318.  
  319. #---end of file---
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement