howto

HOW TO : Use awk to print values larger than certain number

Quick how to on using awk to filter results if a certain value (column) is larger than a set value.

For example, if you have a file (servers.txt) with lines in this format

a_datacenter, servers 20
 error, servers xyz
 b_datacenter, servers 21
 c_datacenter, servers 50

and you want to show only the lines that have server value larger than 20, you can do this in awk by running

grep datacenter servers.txt | awk '$3 > 20  {print ;}' | more

breaking down the commands

grep – parsing down the output to just show the lines containing datacenter

awk – $3 > 20 : Get the third variable (awk seperates text using spaces by default) and check if it is greater than 20

print – print the entire line

HOW TO : Find files, search for content in them, replace the content

The title pretty much says it all :). Here is a quick  one liner, using multiple tools, to look for files in a directory, search for certain content in them and replace them with other content

[code]find -type f | xargs grep -l ORIGINAL_CONTENT | xargs perl -p -i -e ‘s/ORIGINAL_CONTENT/NEW_CONTENT/g’ [/code]

You can theoretically take out the grep (second command) and directly pipe the find output to perl and get the same outcome.

Going over list of the options used

find

  • “-type f” lists all objects of type file in the directory (and sub directories)

grep

  • “-l” lists the names of the files (with relative path) which have the text ORIGINAL_CONTENT in them

perl

  • “-p” forces perl to loop through requests. In this case files
  • “-e” tells perl that the next argument is a perl statement
  • “-i” tells perls to edit the file in place (i.e. no need for an output file)