Text processing with sed/awk

Category: /knowledge /linux
Tags: linux

Sed and awk belong to GNU ‘coreutils’ group. But these two are much more complicated than other utilities due to their programming abilities. Therefore I list them separately for some usage scenarios.

Sed usage examples

use sed to remove leading and trailing spaces

echo $var | sed -e 's/^ *//g' -e 's/ *$//g'

another simple solution is

echo $var | xargs

get the last day of the month

cal "${month}" "${year}" | sed '/^[ \t]*$/d' | tail -1 \
| sed 's/^.* //'

replace a string in a file with sed

sed -ie 's/string_1/string_2/g' *.jsp

AWK usage examples

Awk stands for the names of its authors “Aho, Weinberger, and Kernighan”.

Note: be careful about quotes and semicolon in statements.

Simple Syntax:

awk '/search pattern1/ {Actions}
     /search pattern2/ {Actions}' file

Complete Syntax:

BEGIN { Actions}
{ACTION} # Action for everyline in a file
END { Actions }

'#' is for comments in Awk

example: print 2nd column and the last column of a file.

awk '{print $2,$NF;}' sample_file.dat
awk '/my_string1|my_string2/' sample_file.dat

generate formatted report

awk 'BEGIN {print "Name\tGroup\tParent"; count=0}
    {print $2, "\t", $5, "\t", $NF-1; count++; }
    END {print "---------------\n"; print count," records processed.\n";}' sample_file.dat



  • 如果看不到讨论部分, 请暂时关掉adblock in Firefox/Chrome
  • 本网站使用Javascript实现评论功能, 此处外链对提高您的网站PR没有帮助. (潜台词: 请不要灌水, 谢谢)