Friday 16 October 2009

print only records matching a condition

I want to print the records of ":" seperated fields of every line of a file whose last field i.e my website whose length is not greater than 4k.

Also, Print the records in the same format as input with the same ":" seperator.

cat mydata.log:

name:city:mailid:phone:mywebsite
name1:city1:mailid1:phone1:mywebsite1
.
.
....

One-line:

perl -nlaF":" -e 'if ( length($F[4]) < 3950 ) { $"=":"; print "@F"} ; ' mydata.log

Note:
  • @F array is the perl default array which takes the fields seperated by the delimiter specified after the "F" option.
  • option "n" is for implicit looping.
  • option "l" is for automating line ending.
  • option "a" is for automatic split of line as specified by F" " delimiter.
  • Since mywebsite is the last field we can write $F[-1] in place of $F[4] in the if loop.
  • $" is the seperator by which elements of an array interpolated into a string are joined together.

No comments:

Post a Comment

Tweets by @sriramperumalla