Print all Fields with AWK separated by OFS

This is a variation on the first style: echo “1 2 3 4″ | gawk ‘BEGIN { OFS=” 🙁 “}; {$1=$1; print $0}’ Results: 1 🙁 2 🙁 3 🙁 4 Explanation: the $1=$1 is to rebuild the record, using the current OFS (you can also see http://www.gnu.org/software/gawk/manual/gawk.html#Changing-Fields) Update: (suggested by @EdMorton and @steve) This … Read more

print every nth line into a row using gawk

To print every second line, starting with the first: awk ‘NR%2==1’ file.txt To print every tenth line, starting with the tenth line: awk ‘NR%10==0’ file.txt To use this in a script, add the following to a file called script.awk: BEGIN { print “Processing file” } NR%10==0 END { print “Finished processing” } Then execute: awk … Read more

GNU awk: accessing captured groups in replacement text

With GNU awk: echo abbc | awk ‘{ print gensub(/a(b*)c/, “Here are bees: \\1”, “g”, $1);}’ See manual here to see the difference between gsub and gensub gensub() provides an additional feature that is not available in sub() or gsub(): the ability to specify components of a regexp in the replacement text. This is done … Read more