13.07.2015 Views

Linux System Administration Recipes A Problem-Solution Approach

Linux System Administration Recipes A Problem-Solution Approach

Linux System Administration Recipes A Problem-Solution Approach

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

CHAPTER 9 ■ WORKING WITH TEXT IN FILES975 /533 /~jsmith/mis/nadsat.html486 /favicon.ico291 /rt239 /robots.txt215 /cgi-bin/jkemp/bugreport.cgi9-3a. awk, if, and StringsYou can search for a string in a particular field and print only that. For example, to print a list of all userswho have tcsh as their shell (perhaps so that you can e-mail them to suggest they switch to bash...), usethis:$ cat /etc/passwd | awk -F: '{if ($7 ~ /tcsh/) print $1;}'This sets the field divider to : and then prints the first field (username) if the seventh field (shell)matches tcsh. Alternatively, you could generalize this by searching for users whose shell is not bash:$ cat /etc/passwd | awk -F: '{if ($7 !~ /bash/) print $1}'The if syntax is as follows:'{if (condition) action; }'You can also use the if/else syntax:'{ if (condition) action; else action; }'See recipe 9-2b for regexp syntax, which is the same as for sed.9-4. Manipulating File Contents with PerlThe syntax for reading from a file in Perl is shown in this script, which reads from the auth.log file(which logs authorization attempts) and prints to the output file only those lines that do not match thelocal domain, thus reducing the amount of file you need to check for dubious login attempts.01 #!/usr/bin/perl -w02 use strict;03 my $inputfile = "/var/log/auth.log";04 my $outputfile = "~/authlogout.txt";05 my $searchstring = "192.168";06 open (INPUT, "$outputfile");08 while () {09 print OUTPUT if ! /$searchstring/;10 }11 close INPUT;12 close OUTPUT;193Download at WoweBook.Com

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!