code_junkie

Perl: Grabbing the nth and mth delimited words from each line in a file

Nov 11th, 2011
94
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.11 KB | None | 0 0
  1. xxx.xxx.xxx.xxx hostname #comments. i.dont. care. about
  2.  
  3. if($line =~ m/(S+)s+(S+)/) {
  4. $ip = $1;
  5. $hostname = $2;
  6. }
  7.  
  8. my @arr = split(/ /, $line);
  9. $ip = $arr[0];
  10. $hostname = $arr[1];
  11.  
  12. #!/usr/bin/perl -n
  13. chop; # strip newline (in case next line doesn't strip it)
  14. s/#.*//; # strip comments
  15. next unless /S/; # don't process line if it has nothing (left)
  16. @fields = (split)[0,1]; # split line, and get wanted fields
  17. print join(' ', @fields), "n";
  18.  
  19. @fields = (split /:/)[0,2,4..6];
  20.  
  21. perl -ane 'print "@F[0,1]n";'
  22.  
  23. perl -ape '$_="@F[0,1]
  24. "'
  25.  
  26. perl -nae 'print "$F[0] $F[1]n";'
  27.  
  28. perl -nae 'print "$F[0] $F[1}n";
  29.  
  30. -a turns on autosplit mode when used with a -n or -p. An implicit split
  31. command to the @F array is done as the first thing inside the implicit
  32. while loop produced by the -n or -p.
  33.  
  34. LINE:
  35. while (<>) {
  36. ... # your program goes here
  37. }
  38.  
  39. while (my $line = <ARGV>) {
  40. chop $line;
  41. $line =~ s/#.*//;
  42. next unless $line =~ /S/;
  43. @fields = (split ' ', $line)[0,1];
  44. print join(' ', @fields), "n";
  45. }
Add Comment
Please, Sign In to add comment