awk one-liners

This is a collection of as many one line awk programs I can come up with. More will be added in time.
# remove newlines from a file
awk '{printf $0}' file

# print only even lines of a file
awk 'NR%2' file
# print only odd lines of a file
awk '!(NR%2)' file

# print second column of data file
awk '{print $2}' file
# print last column of data file
awk '{print $NF}' file

# print the sum of the 4th coulumn of a file
awk '{ sum+=$4 }END{ print sum }' file
# print the sum of column 4 in a csv (comma separated variable) file
awk 'BEGIN{ FS="," }{ sum+=$4 }END{ print sum }' file.csv

# print the number of characters in a file
awk '{ c+=length+1 }END{ print c }' file
# print the number of words in a file
awk '{ c+=NF }END{ print c }' file
# print the number of lines in a file
awk 'END{ print NR }' file

# double space a file
awk '{print; print ""}' file
# undo double spacing
awk 'NR%2' file

# number each line of a file
awk '{printf "%4d %s\n",NR,$0}' file

# count the number of lines matching a regex
awk '/regex/{c++}END{print c}' file

# remove leading whitespace from lines
awk '{a=gensub(/^[ \t]*(.*)$/,"\\1","g"); print a}' file
# remove leading and trailing whitespace from lines
awk '{a=gensub(/^[ \t]*(.*)[ \t]*$/,"\\1","g"); print a}' file

# print first ten lines of a file
awk 'NR<=10' file
# print lines 10 to 20 of a file
awk 'NR>=10&&NR<=20' file

# only print lines that match a regular expression (same as grep)
awk '/regex/' file
# only print lines that DO NOT match a regular expression (same as grep -v)
awk '!/regex/' file

# print section of file from regular expression to end of file
awk '/regex/{v=1}v' file

# remove all blank lines
awk '!/[ \t]*/' file     # method 1
awk 'NF>0' file          # method 2

# remove every 8th line
awk 'NR%8' file
# print every 8th line
awk '!(NR%8)' file

# print only lines that have less than 50 characters
awk 'length<50' file
# print only lines that have less than 5 words
awk 'NF<5' file




Choose your way out: [sed2awk project] [awklores home]

Copyright James Lyons - 2007 - No reproduction without permission
dsplabslinux blogtravel blogcryptographymy homepage