Jump to content

Linux/Basic commands/awk

From Wikiversity
(Redirected from Awk)

AWK is a language/utility designed and used mainly for text processing.


Basic Examples

[edit | edit source]
  • Prepend a variable string ($STRING_TO_PREPEND) at the beginning of every line
cat file.txt | awk '{print "'$STRING_TO_PREPEND' "$0}'[1]

In case text to prepend is a variable ($PREPEND_TEXT_VAR):

echo "$ORIGINAL_TEXT" | awk -v AWK_PREPEND_VAR="$PREPEND_TEXT_VAR" '{print AWK_PREPEND_VAR" "$0}'

Prepend time before every line

echo "$ORIGINAL_TEXT" | awk -v time="$(date)" '{print time" "$0}'


  • Remove leading spaces at the beginning of a line:
awk ' {$1=$1} 1 '[2]
  • Print line if field value is larger than:
awk '$FIELD_NUMER>VALUE'
Example: awk '$4>3.1416'

Activities

[edit | edit source]
  1. Read stackoverflow awk questions: https://stackoverflow.com/questions/tagged/awk?tab=Votes

See also

[edit | edit source]
  • sed
  • tr to replace or remove specific characters from input data
  • grep and ag
  1. https://serverfault.com/questions/72744/command-to-prepend-string-to-each-line
  2. https://catonmat.net/awk-one-liners-explained-part-two