awk command

  • print the second line
    awk 'FNR == 2 {print}'
  • print the second field
    awk '{print $2}'
  • print the third field of the fifth line
    awk 'FNR == 5 {print $3}'
  • print the j'th field of the i'th line
    awk -v i=5 -v j=3 'FNR == i {print $j}'
  • print the third field of the fifth line when second column contains abc
    awk '$2 ~ /abc/ && FNR == 5 { print $3 }'
  • filter lines match with regexp
    awk '/regexp/'
  • filter lines not match with regexp
    awk '!/regexp/'
  • filter first five lines
    awk 'NR < 6'
  • filter lines from number 6 to number 18 and not match 'foobar'
    awk 'NR>=6 && NR<=18 && !/foobar/'
  • filter lines which second character of seventh field is "5"
    awk 'substr($7,2,1)=="5"'
  • print lines and replaced the first occurence number with 'z'
    awk '{sub(/[0-9]+/,"z");print}'
  • print lines and replaced all occurence number with 'z'
    awk '{gsub(/[0-9]+/,"z");print}'
  • print string fifteen characters from second character of line
    awk '{print substr($0,2,15);}'
  • print a section from regular expression to end of file
    awk '/regex/,0'
  • print all sections from line match regex1 to line match regex2
    awk '/regex1/,/regex2/'
  • print lines each section from line match regex and have same 6th field value with match line
    awk '/regex/,0 !a{a=$6} $6==a'
    awk -v v1="regex" '$0~v1,0 !a{a=$6} $6==a'

related: