Usage of unix tools Find,Sed and awk


Sed, Awk and Find are the excellent unix tools.Following are few problem statements where use of these tools made the work easy.Have a glimpse if these are useful to you as well.

  1. Dump only CPU usage and process of the server to a file.
      Top –n 1 –d  |  sed ‘1,6d’ |   awk ‘{print  $8 $NF }’ > dump.txt

  1. Find a pattern “EMC2” which exists in multiple files under current directory and replace the pattern with “CISCO” in all the files.
      Find .  –type f    | xargs sed –i ‘s/EMC2/CISCO/g’
      OR find  . –type f   -exec sed –i ‘s/EMC2/CISCO/g’ {} \;

  1. Calculate the number of lines between a line containing pattern “XYZ” & a line containing pattern “ABC” in a file.
Sed –n ‘/XYZ/,/ABC/p’ | wc –l

  1. List the top 3 largest files in a sub-directory.
      find  /root/dir/  -type f -exec ls -las {} \; | sort -n -r | head -3

  1. Calculate the number of Normal users created in a unix server         
       last | awk –F”:” ‘$4  > 1000 {print}’| wc -l
6.  Replace "root" by "admin" and "user" by "superuser" in a file only from line number 10 to the end of file.
    sed -i '10,/^END/{ s/root/admin/g  s/user/superuser/g  p}' filename
7. To extract data from beginning to every fourth line:
sed -n '1~4P'  
8. To get the IP address from a file:
    grep -Eo '[1-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}'

9.To execute the commands in sub-shell and current shell"
{}=> executes the commands in current shell.
()=> Executes the commands in sub-shell.
 example:
{echo "xyz"; exit} This exits from the scripts.
(echo "xyz"; exit) This doesnt exit from the script as this says the child shell is exited not the parent one.
10. How to save readonly files:
:w !sudo tee % >/dev/null


Comments