awk

From wikieduonline
Revision as of 10:59, 1 February 2024 by Welcome (talk | contribs) (→‎Related)
Jump to navigation Jump to search

Examples

  • cat file.txt | awk '{print $1}'


  • 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 lines if field fith value ($5) is smaller than 100:
awk '$FIELD_NUMER>VALUE'
Example: awk '$5<100'
  • Print all lines after some text[3]
awk '/TEXT_TO_SEARCH/{f=1}f' file
  • Print every 3 lines:
awk 'NR%3==1' your-file.txt
  • Print last field from a file
awk '{print $NF}' your-file.txt
  • Print last but one field from a file
awk '{print $(NF-1)}' your-file.txt
  • Print line only if a field meet a condition, bigger or smaller than, example field 4 bigger that 134:
awk '$4 > 134 {print}' your-file.txt
ps --no-headers -o "rss,cmd" -C php-fpm7.2 | awk '{ sum+=$1 } END { printf ("%d%s\n", sum/NR/1024,"M") }'

Related

Activities

See also

Advertising: