AWK: pattern and actions

September 26th, 2010 79 views Leave a comment Go to comments

Regular Expression Typography

We write action in curly braces. But pattern can be written outside. Like;

Syntax

	pattern { action }

Example

	awk 'NR==52 {print $0;}'
Pattern decides “what to search?”. While action decides “what to do?”.

For example you want to remove all spaces & tabs from all fields of a file.

Here, first you need to find out text contains spaces & tabs (pattern) only. So you can replace it by blank character. This is called action.

Example:

awk ‘/article-stack\.com/’ post-contents.txt

Above command will filter & print (as its default nature) all the lines which contain “article-stack.com”. Don’t worry about how we are doing. That I’ll explain in next session. Here, “/article-stack\.com/” is called pattern.

Now instead of printing complete line, you may prefer to print first some words or characters. Sometimes you just want to delete the matched pattern from the file. This all activity is called action.

I am not giving any example for this. Because you need to learn basic structure and syntax of AWK first.

You can understand patterns deeply only when you are clear with Regular Expressions.

Amit Gupta

Hey! this is Amit Gupta (amty). By profession, I am a Software Eng. And teaching is my passion. Sometimes I am a teacher, as you can see many technical tutorials on my site, sometimes I am a poet, And sometime just a friend of friends...

  1. No comments yet.