217324234.xlsx.
ms_office
HANDS ON
S.NO CATEGORY COMMANDS
OPENING SCRIPT EXTENSION RUN INCLUDE
SHELL
bash .sh ./filename or sh filename.sh #!/bin/bash
INTRODUCTION
1 BASICS
INPUT ASSIGNM
2 OPERATIONS ASSIGNMENT USER INPUT INCLUDE SPECIAL MEANING PRINT STRING PRINT STRING WITH VALUE var=10, a=$var read a expr 2 \* 3 $myvar myvar value: $myvar
space needed between operators and not in assignment
ARITHMETIC PRINT VALID OPERATORS VARIABLES SCALARS ARRAYS ASSOCIATIVE ARRAYS
Date = `date` result=`expr $num1 \* $num2` echo $result +,-,*,/,%,<,<=,>,>=,<<,>>
SYMBOLS
3 SYMBOLS COMMENT STATEMENTS SEPERATOR ESCAPE SEQUENCE VARIABLE STRING COMMAND EXECUTION BLOCK OF CODE NO OPERATION TEST CONDITION STANDARD OPERATORS # ; \ $ "" OR '' ` ` OR $() {} : [] STDIN(0) STDOUT(1)
217324234.xlsx.ms_office STDERR(2) REDIRECTION INPUT < OUTPUT > APPEND MODE >>
3 DEBUG
EXECUTED COMMANDS LINES READ
sh -x filename.sh sh -v filename.sh
LOOPING
for loop-variable in members do command command done ,- can also be used for the block instead of do done 4 LOOP FOR
FOREACH
NA while [ condition ] do command command done There MUST be a space after [ and before ]
WHILE
217324234.xlsx.ms_office until [ condition ] do command command done UNTIL 5 CONDITION EQUAL TO NOT EQUAL TO LESS THAN GREATER THAN LESS THAN OR EQUAL TO GREATER THAN OR EQUAL TO $a -eq 0 , $STRING = $STRING2 $a -ne 1 , $STRING != $STRING2 $a -lt 2 $a -gt 3 $a -le 4 $a -ge 5
CONDITION
BRANCHING
if condition1 then commands1 else commands3 fi 6 BRANCHING IF ELSE if condition1 then commands1 elif condition2 then commands2 else commands3 fi IF ELSE IF ELSE case $cal in add) ;; sub) ;; mul) ;; div) ;; esac
SWITCH CASE
217324234.xlsx.ms_office
UNLESS 7 COMMAND LINE SCRIPT NAME ADDITIONAL ARGUMENTS ARGUMENT COUNT ENUMERATES EXIT VALUE OF LAST COMMAND LINE NUMBER REMOVES NEW LINE REMOVES LAST CHARACTER anonymous VARIABLE
NA $0 (./FILENAME.sh) $1 $# $@ OR $* $?
COMMAND L
FUNCTI
function func_name { Body of function } Note:- all the arguments passed to the function will be stored to $1, $2 variables 8 FUNCTIONS DEFINITION
IMPORT 9 SUB SHELL RUNNING IN PARENT CHILD
source ./scripname . ./FILENAME.sh Default one
EX
217324234.xlsx.ms_office .bash_profile .bashrc .bash_logout 10 CONFIGURATION 11 SIGNALS TRAP A SIGNAL IGNORE A SIGNAL RESET A SIGNAL $ trap command signal $ trap signal $ trap signal
LIST DATA
12 LISTS
CREATE LIST OPERATIONS
NA INDEX SORT CONCATENATE APPEND LENGTH INSERT RANGE DELETE REVERSE DELETE AT LAST
13 NAMESPACE
It encapsulates the commands and variables to ensure that they won't interfere with the commands and variables of other namespaces
STRING O
13 STRING EQUAL
LAST
NA
217324234.xlsx.ms_office LENGTH RANGE REPLACE INDEX MATCH
NA
ADDITIONAL OPERATIONS TO BINARY STRING TO TCL STRING
SCAN
parses string using conversion specifiers
SCOPE O
14 SCOPE 15 INTERNALS NA NA
FILE H
16 FILE ALL COMMANDS
OPEN SEEK
NA
MODE diamond operator 17 ARRAYS INSERT AT LAST
TOUR W
ARRAY LENGTH INSERT AT FIRST REMOVES AT LAST REMOVES AT FIRST REVERSE SORT
NA
217324234.xlsx.ms_office JOIN SPLIT NA
ASSOCIATIVE ARRAY
DECLARE DEFINE ITERATE KEYS VALUES
MAY I
18 HELP
INFO
man command
SOURCE SOCKET
NA
ERROR INFO
WINDOW SHELL
REGULAR
217324234.xlsx.ms_office
19 PATTERN MATCHING
SYNTAX
OPTIONS
!~
/g /i /x
s / pattern / replace /
tr / characters / repl-characters / split ( /Pattern/, String )
REFERENCING &
217324234.xlsx.ms_office
HANDS ON SCRIPTING
TCL INTRODUCTION TO VARIOUS SHELLS
tclsh .tcl tcl filename.tcl perl -e commands .pl perl filename.pl #!/usr/bin/perl ALL LINES END WITH ; $name = Aricent Tech; ( $a, $b) = ($c, $d); # Same as $a=$c; $b=$d; $inputline = <STDIN>;
PERL
INPUT ASSIGNMENTS AMD OUTPUT
set a 22,set b $a gets stdin var expr 2 \* 3 also expr 2*3 works fine set b {[expr $a+10]} "a is $a"
print Length of name : , length($name), \n;
spaces not needed between operators
print "@array"; #print whole array with spaces print @array; #print whole array without spaces
set Date [date] set b [expr $a+10] puts "x is $x"
system(date);$Date = `date`; $S = $A + $B print "@array"; print $s;
set student(name) John
$scalars @arrays %associative_arrays # , =begin =cut
SYMBOLS AND OPTIONS
#
stdin stdout
STDIN(0) STDOUT(1)
217324234.xlsx.ms_office stderr STDERR(2)
ERROR HANDLING
catch {expr {2 +}} msg error "bad argument"
use warnings use strict
LOOPING CONSTRUCTS
The next command starts the next iteration of the loop. The last command immediately exits the loop in question. The redo command is used to start processing of the current iteration again.
for {set x 0} {$x<10} {incr x} { puts "x is $x" }
for (INITIALIZATION; WHILECONDITION;INCREMENT/DECREMENT) { Statements executed } foreach my $LOOP_VAR (@ARRAY) { #statements executed for each array element }
foreach i {1 2 3 4 5} {
set n [expr {$n + i*i}] }
while {[gets $chan line] >= 0} { puts "[incr lineCount]: $line" }
while (CONDITION) { # Code block executed if condition is true. }
217324234.xlsx.ms_office
NA
until (CONDITION) { # Code block executed while condition is false. } $STRING eq $STRING2, $a == 0 $STRING ne $STRING2, $a != 1 $STRING lt $STRING2, $a < 2 $STRING gt $STRING2, $a > 3 $STRING cmp $STRING2, $a <= 4 $a >= 5 if (CONDITION) { # Code block executed if condition is true.
CONDITIONAL OPERATORS
$a == 0 , $STRING == $STRING2 $a != 1 , $STRING != $STRING2 $a < 2 $a > 3 $a <= 4 $a >= 5
BRANCHING STATEMENTS
if {expr1} { puts "vbl is one ; #body1 } else { puts "vbl is not one or two" } if {expr1} { puts "vbl is one ; #body1 } elseif {$vbl == 2} { puts "vbl is two } else { puts "vbl is not one or two" }
} else { # Code block executed if condition is false. }
if (expr1) { puts "vbl is one ; #body1 } elsif ($vbl == 2) { puts "vbl is two } else { puts "vbl is not one or two" }
set foo "abc" switch abc a - b {expr 1} $foo {expr 2} default {expr 3}
217324234.xlsx.ms_office unless (CONDITION) { # Code block executed if condition is false. } elsif (CONDITION FALSE 1) { # Code block executed if condition is true. } else (CONDITION FALSE 2) { # Code block executed if condition is true. } NA
COMMAND LINE OPERATIONS
$argv0 $argv1 $argc $argv $0 for script name. Arguments stored in @ARGV $ARGV[0] $#ARGV+1 @ARGV $. chomp ($price); chop($price); $_
FUNCTIONS USAGE
sub <sub_name> (Arguments) { } Parameters passed to a subroutine can be accessed in a subroutine using a special variable @_ Package package_name; BEGIN { # initialization statement } Sub function_name { #body of function } Return 1; return $s END { #clean up statement } Save this file as package_name.pm use package_name; package_name::function_name();
proc decr {x {y 1}} { expr $x-$y }
proc sum args { set s 0 foreach i $args { incr s $i } sum 1 2 3 4 5 source ./scripname
EXTRAAS
catch {exec grep foo << $input | wc} error
217324234.xlsx.ms_office
fconfigure $f -translation binary FOR BINARY ENCODED FILE HANDLER
LIST DATA STRUCTURES
set tList {{one} {two} {three}} Or set tList [list one two three] Or set tList *split one .two .three .+ lindex {a b {c d e} f} 2 --> c d e lsort {red green blue} -->blue green red concat a b {c d e} {f {g h}} -->a b c d e f { g h } lappend var 2 --> 2 APPENDED IN END llength {a b c d e} --> 5 linsert $tList 1 --> INSERT IN INDEX 1 lrange {a b c d e} 0 1 --> RETURNS a b
namespace eval Counter { namespace export bump variable num 0 proc bump {} { variable num incr num } } One can then access proc bump using Counter::bump from global namespace
STRING OPERATIONS
set isitEqual [string equal $x1 $string] ; # Returns 1 if equal else 0. string last a 0a23456789abcdef 15 # will return 10. Here index within which the occurrence has to be found is 15.
217324234.xlsx.ms_office string length string ; string range string first last string replace string first last ?newstring? string index string charIndex string match ?-nocase? pattern string regexp format split binary regsub scan join append formatString ?arg arg ...? string formatString ?varName varName ...? set string "08:08" ;# *Not* octal! if {[scan $string "%d:%d" hours minutes] != 2} { error "not a valid time string" }
SCOPE OF VARIABLES
global uplevel upvar info rename trace my local
FILE HANDLING
open gets seek flush glob file close read tell cd pid puts source eof pwd open (FILE_HANDLE, EXPR ); EXPR = MODE + FILENAME open (FILEHANDLE, "<filename")
set fl *open trn w++ seek $f -10 end
< - READ, > - WRITE, >> - APPEND <> - They instruct Perl to read one line of input from the file handle inside the operators.
TOUR WITH ARRAYS
push (@array1, $scalar1); $numberOfElements = @array; scalar @array; $#array +1; $number = unshift ( @animals, " lion ); $snake = pop (@animals); $lion = shift (@animals) @a = reverse (@a); @sort_animals = sort (@animals);
217324234.xlsx.ms_office $URL = join (., @url); @fields = split ( / : / , "1:2:3:4:5");
set student(name) John
% geography = (Bangalore , India , London, England); % geography = (Bangalore" => India", London" => England"); ($city, $country) = each %geography; @cities = keys %geography; @countries = values %geography;
MAY I HELP YOU
% info commands s* socket subst split source switch spinbox scale set scan seek scrollbar selection string perldoc -f perlfunction man n command Evaluate a file or resource as a Tcl script source <filename> socket option addr port server option creates server socket Global variable errorInfo provides stack trace set errorInfo Wish: Windowing Shell button .hello -text "Hello, world" -command exit pack .hello
REGULAR EXPRESSIONS
217324234.xlsx.ms_office
regexp -all -- {\S+} $line
pattern_to_match =~ /pattern/; if (m/$pattern/) { print "Found $pattern \n"; } is just the negative of =~ global -This option finds all occurrences of the pattern in the string. A list of matches is returned. case-insensitive - This option ignores the case of characters in the string. Ignore whitespaces Replaces the sub- string matched by pattern with replace (once) and returns the number of replacements (obviously 0 or1) Translates characters (one by one), as specified by characters with repl-characters and returns the number of replacements.tr is always global my @fields = split ( /\s+/, $string);
REFERENCING & DE REFERENCING
217324234.xlsx.ms_office
PYTHON
python .py python filename.py, execfile('script.py') #!/usr/bin/python
x = [0,1,2], writer=raw_input('Please enter') or year=int(year) \*
os.system(command) or from datetime import date now = date.today() s=s+i print 'Hello world' OR print s
#, Triple quotes - multi line string
sys.stdin sys.stdout
217324234.xlsx.ms_office sys.stderr
try: n = float(s) numbers.append(s) except ValueError, msg: not_numbers.append(str(msg))
for i in range(1,7):
while condition: action
217324234.xlsx.ms_office
s == 'string', a == 0 a != 1 , STRING != 'STRING2' a<2 a>3 a <= 4 a >= 5
if condition: action
if condition1: action1 elif condition2: action2 else: action3
217324234.xlsx.ms_office
sys.argv[0]
sys.argv
def func(args): Actually returns a value anyway: 'None'
import module module.submodule.x OR from module import submodule submodule.x map(func,list), reduce(func,list), filter(func,list)
217324234.xlsx.ms_office
shoplist = ['apple', 'mango', 'carrot', 'banana'] olditem = shoplist[0] shoplist.sort() shoplist.append('rice') len(shoplist) shoplist[1:3] del shoplist[0] shoplist.reverse() shoplist.pop()
re MODULE has re.compile, obj.match, re.search, obj.group,re.split,re.findall, re.finditer, re.sub,
217324234.xlsx.ms_office
hollow=hollow.replace('Shadow','Light') index=song.find('a')
Built-in (Python),Global (module),Local (function)
F=open(filename,w) f.write(poem) f.close() line = f.readline()
TUPLE zoo = ('wolf', 'elephant', 'penguin') new_zoo = ('monkey', 'dolphin', zoo) len(new_zoo) new_zoo[2][2] --> penguin
217324234.xlsx.ms_office
DICTIONARY ab = { 'Swaroop' : 'swaroopch@byteofpython.info', 'Larry' : 'larry@wall.org', 'Matsumoto' : 'matz@ruby-lang.org', 'Spammer' : 'spammer@hotmail.com' } ab['Guido'] = 'guido@python.org' del ab['Spammer'] ab.items(): ab.has_key('Guido')
help()
217324234.xlsx.ms_office
import re seq = "MAKEVFSKRTCACVFHKVHAQPNVGITR" zinc_finger = re.compile('C.C..H..H') # compile regular expression pattern print zinc_finger.findall(seq)