Awesome awk oneliners

I use awk very often, here are some of the one-liners i use often.

Awesome awk oneliners
Photo by Vincent van Zalinge on Unsplash

I use awk very often, here are some of the one-liners i use often.

replace multiple spaces with single spacecommand | awk '{ gsub(/[ ]+/," "); print }'

  • gsub is a global substitution function.
  • [ ]+ represents one or more whitespaces.
  • “ “ represents one white space.

trim leading and trailing spacescommand | awk '{ gsub(/^[ \t]+|[ \t]+$/, ""); print }'

  • gsub is a global substitution function
  • ^[ \t]+ represents leading whitespaces
  • [ \t]+$ represents trailing whitespaces
  • “” represents nothing (trim the string)

replace string with another one only in lines contain specific stringcommand | awk '/,/{gsub(/ /,""); print}'

  • /,/ search for comma
  • gsub is a global substitution function
  • / /,”” replace space with nothing

print lines where column equals values based on conditionscommand | awk -F, '(tolower($6)~"rhel" || tolower($6)~"linux"){print $0}'

  • ~ contains value
  • -F, delimiter is comma
  • tolower , this function converts upper case characters to lower case

replace string with another string without conditionscommand | awk 'gsub(/ /,"")'

  • gsub is a global substitution function
  • / /,”” replace space with nothing

print specific column numberscommand | awk -F, '{print $1,$2,$7}'

$1, $2, $7 print 1st, 2nd and 7nth column of each line

Insert text between variablescommand | awk -F, '{print $1";"$7"_prd;\""$2"\";gnome-terminal -- ssh -J $ssh_username@gateway1 $ssh_username@server1"}'

  • just append text after variable
  • “ can be inserted like this “\””

replace first occurrence of string

command | awk '{sub(/,/,"1,")}1'
  • sub replaces the first occurrence of a string

replace last occurrence of stringcommand | rev | awk '{sub(/;/,",")}1' | rev

  • rev reverses incoming text