Shell/Regex/Perl Quick Reference

Shell/Regex/Perl Quick Reference

Shell Information $? = exit status of previous command #!/bin/bash read varName first line of file sets value of variable varName to next line read from stdin command > filename write output to filename 'str ' = str "str " = str with variables interpolated command >> file `command ` = output of command as string append output to filename Zero exit status means true/successful command 2> filename Non-zero exit status means false/failure write stderr to filename test expression command >file 2>&1 returns expression result as exit sta- write stdout and stderr to filenametus integer operators: -lt,-gt,-eq,-ne,-ge,-le <filename command string operators: =, -z, -n input from filename file operators: -d, -e, -f, -s, -nt command1 | command2 exit Number pipe output from command1 terminate script with exit status Number as input to command2 if Commanda ; then command1 && command2 Commands1 execute command2 if command1 elif Commandb ; then has exit status zero Commands2 else command1 || command2 Commands3; execute command2 if command1 fi does not have exit status zero case Word in $((expression )) Pattern1) Commands1 ;; expression evaluated as arithmeticPattern2) Commands2 ;; ... $0 = name of currently executing command *) Commandsn ;; $1,$2,$3,... = command-line arguments esac $# = count of command-line arguments 1 while Command ; do . (dot) Commands matches any single character done (pattern ) matches pattern for var in Word1 Word2 ... do Anchors: Commands done ^pattern matches pattern at the start of a line # Display lines from file pattern $ count=0 matches pattern at the end of a line while read line do Selection: count=$((count + 1)) echo "Line $count: $line" [charList ] done <file matches any single charac- ter in charList # Interactively rm files in current dir [^charList ] for f in * matches any single charac- do ter not in charList echo -n "Remove $f? " pattern1|pattern2|pattern3|... read answer matches any of the patternis if test $answer = y then charList s use c1-c2 to de- echo $f note char ranges, and fi meta-characters lose their special meaning in- done side charList s Regular Expressions Repetition: Atomic Patterns: pattern ? zero or one occurrences of pattern letters, digits, punctuation (except those be- pattern * low) zero or more occurrences of pattern match any occurrence of themselves pattern + \. \* \+ \? \| \^ \$ \[ \] one or more occurrences of pattern match any occurrence of the second char- acter \w matches alphanumeric, including '_' 2 \s matches whitespace Perl Information \d matches numeric #!/usr/bin/perl -w - first line of file \b word boundary $var - simple scalar variable pattern {N ,M } $var[n ]- n th element of array matches N to M occur- $var{val }- ele- rences of pattern ment of hash for key val @var - entire array, or length in scalar context @var[i,j,k ]- slice from array %var - entire hash 'str ' = str "str " = str with variables interpolated `command ` = output of command as string empty string and numeric zero are FALSE anything else is TRUE $_ - default input or matched pattern $0 - name of the Perl script file $? - exit status of last system command $$ - process id of Perl runtime process @ARGV - command line arguments %ENV - environment variables %INC - path for included scripts Arithmetic operators: + - * / ** (power) % (mod) .. (range) Relational operators: == != < > <= >= (nu- meric) eq ne lt gt le ge (string) =~ !~ (pat- tern) Logical operators: 3 ! (NOT) && (AND) || (OR) (any of &, (, ) can be omitted) not and or (low-precedence ver- sions) sub name block - subroutine definition Bitwise operators: - in block, @_ holds args ~ (NOT) & (AND) | (OR) ^ (XOR) String operations: Arithmetic: . concatenation abs expr x repetition returns absolute value of expr sin, cos, atan2 expr $var = expression ; returns geometric function on expr $var ++; ++$var ; int expr $var += expr ; $var -= expr ; ... returns integer portion of expr $var =~ s/pattern /replacement /; rand [ expr ] $var =~ tr/chars /chars /; returns random value in 0..expr returns random in 0..1 if no expr sqrt expr block = { statement1; statement2; ... } returns square root of expr time while (condition ) block returns # seconds since Jan 1 1970 until (condition ) block do block while (condition ) Conversions: do block until (condition ) chr expr for (init ;test ;next ) block returns char represented by expr foreach $var (list ) block localtime expr converts expr into a date/time string last - exit the loop ord expr next - go to next iteration returns ascii for first char in expr redo - restart this iteration Strings: if (condition1) block1 chomp list elsif (condition2) block2 removes line end- ... ings from each string in list elsif (conditionn) blockn chop list else blockn+1 removes last char from each string in list index str ,substr [,offset ] &subroutine (arglist ); returns position of substr in str (or -1) 4 and starts looking from offset, if given ues of list onto end of array length str reverse list returns # characters in str returns the list in reverse order lc str shift @array uc str pops off and returns first ele- returns lower/upper case version of str ment from array lcfirst str sort [block |subr ] list ucfirst str returns a sorted array of val- returns str with 1st char in lower/upper caseues from list substr str ,offset [,len ] block /subr can be used to define order- returns substring of str start- ing ing at offset split /pattern /,string extending to end (or len chars, if sup- split string at pattern s (de- plied) fault \s) returns an array of split fragments Arrays: unshift @array ,list delete $hash {key } pushes val- remove key and its value from hash ues of list onto front of array grep expr ,list grep block ,list Files/Directories: returns array of all elements from list Tests (argument is either filename or filehandle) for which expr /block evaluates to true -r -w -x - file is read/write/executable join expr ,list -e -z - file exists, has zero size returns a string containing all elements -s - file size in bytes from list , separated by expr -M - time since file modified keys %hash -f -d - file is plain file, directory values %hash chmod list returns an ar- change permissions of files in list ray of all keys/values in hash first list element must be numeri- map expr ,list cal mode map block ,list link oldfile ,newfile evaluates expr /block for each element symlink oldfile ,newfile of list and returns array of results creates a link/symlink pop @array mkdir dirname ,mode pops off and returns last ele- rmdir dirname ment from array create/remove directory dirname push @array ,list unlink list , pushes val- remove all files named in list 5 System interation: Input/Output: chdir expr <handle > Changes working directory to expr in scalar con- die expr text, read next line from handle print value of expr to STDERR and exit in array con- exit expr text, read all lines from handle terminate with exit status expr <> sleep expr reads from in- suspend program execution for expr secs put stream made from all files system expr specified in @ARGV or else from STDIN execute expr as a Unix command close handle closes the file/pipe associ- CGI.pm ated with handle header() flock handle ,op return HTTP header performs file-locking opera- param() tion on handle list of parameters op is a combination of 1(shared), param(name ) 2(exclusive), 4(non-block), 8(unlock) value of parameter name getc handle param(name , value ) returns next character from handle set parameter name to value open handle ,filename start_html, end_html opens a file and asso- start_form, end_form ciates it with handle textfield, textarea, submit, hidden conventions for specifying filename : short cuts to produce HTML "<file " open file for input "file " open file for in- put; == "<file " ">file " open file for out- put and truncate ">>file " open file for appending "|cmd " open pipe to write to cmd "cmd |" open pipe to read from cmd print [handle ] expr displays expr on handle (STDOUT) stream printf [handle ] fmt ,list formats list using fmt and displays 6.

View Full Text

Details

  • File Type
    pdf
  • Upload Time
    -
  • Content Languages
    English
  • Upload User
    Anonymous/Not logged-in
  • File Pages
    6 Page
  • File Size
    -

Download

Channel Download Status
Express Download Enable

Copyright

We respect the copyrights and intellectual property rights of all users. All uploaded documents are either original works of the uploader or authorized works of the rightful owners.

  • Not to be reproduced or distributed without explicit permission.
  • Not used for commercial purposes outside of approved use cases.
  • Not used to infringe on the rights of the original creators.
  • If you believe any content infringes your copyright, please contact us immediately.

Support

For help with questions, suggestions, or problems, please contact us