Unit 2
Unit 2
Unit 2
wget
http://home.adelphi.edu/~pe16132/csc271/note/scripts/demoS
hare
The read Command
(continued)
Read from stdin (screen)
Read until new line
Format Meaning
read answer Reads a line from stdin into the variable answer
read first last Reads a line from stdin up to the whitespace, putting the
first word in first and the rest of the of line into last
read Reads a line from stdin and assigns it to REPLY
read –a Reads a list of word into an array called arrayname
arrayname
read –p prompt Prints a prompt, waits for input and stores input in REPLY
read –r line Allows the input to contain a backslash.
Shortcut to Display Lots of Words
• Here file:
– You give it the end token at the start
– Type a list
– Type the end token to end
– cat << Here
words
Here
wget
http://home.adelphi.edu/~pe16132/csc271/note/scripts/
nosy
Numbers
• Assumes variables are strings
• Math operations on strings are essentially
ignored
– Normalvar=1
– 3+$normalvar yields 3+1
• Must force consideration as number
– Create variable with declare - i
– Surround your mathematical statement with (( ))
wget
http://home.adelphi.edu/~pe16132/csc271/note/scripts/
numbers
Different Base Nums: Octal, Hex
wget
http://home.adelphi.edu/~pe16132/csc271/note/sc
ripts/ifscript
Testing Strings vs Numbers
Comparing numbers
• remember (( ))
• -eq , -ne, -gt, -ge, -lt, -le
Comparing strings
• Remember [[ ]]
• Remember space after [
• =
• !=
• Unary string tests
– [ string ] (not null)
– -z (0 length)
– -n (some length)
– -l returns the length of the string
wget
http://home.adelphi.edu/~pe16132/csc271/note/sc
ripts/ifscriptnum
Echo
Echo command is well appreciated when trying to debug scripts.
Syntax : echo {options} string
Options: -e : expand \ (back-slash ) special characters
-n : do not output a new-line at the end.
String can be a “weakly quoted” or a ‘strongly quoted’ string. In
the weakly quoted strings the references to variables are
replaced by the value of those variables before the output.
As well as the variables some special backslash_escaped symbols
are expanded during the output. If such expansions are
required the –e option must be used.
test Command Operators – String Test
Test Operator Tests True if
wget
http://home.adelphi.edu/~pe16132/csc271/note/script
s/forscript
while Command
• The while command evaluates the command
following it and, if its exit status is 0, the commands
in the body of the loop are execeuted.
• The loop continues until the exit status is nonzero.
• Format:
while command
do
command(s)
done
wget
http://home.adelphi.edu/~pe16132/csc271/note/script
s/numm
The until Command
wget
http://home.adelphi.edu/~pe16132/csc271/note/scrip
ts/runit
Commands Used With select
• select will automatically repeat and has do
mechanism of its own to terminate. For this
reason, the exit command is used to
terminate.
• We use break to force an immediate exit
from a loop (but not the program).
• We use shift to shift the parameter list one
or more places to the left, removing the
displaced parameters.
wget
http://home.adelphi.edu/~pe16132/csc271/note/scrip
ts/dater
SELECT for a menu
• – creates menus that don’t stop until you break
out of the loop
– Syntax:
• PS3=”Whatever you want your prompt to be for the menu “
• select var in options list (and use ‘ ‘ to surround 2 word
options)
• do
• Command(s)
• done
– Ex: select program in `ls –F` pwd date ‘some other
option’ exit
File IO
• read command
– Reads from stdin unless directed with < or |
ls | while read line
do
echo The line is "$line"
done
• Write to a file using redirection >
ls | while read line
do
echo The line is "$line"
done > outputfile
• ‘-i’
– Ignores case.
• ‘-v’
– Inverts the matching. When used, grep will print
out lines that do not match the pattern
• ‘-e pattern’
– Pattern is the pattern. This can be used to specify
multiple patterns, or if the pattern starts with a ‘-’.
A line only has to contain one of the patterns to
be matched.
Examples using ‘-i’, ’-v’, and ‘-e’
• ‘-n’
– Prefixes each line of output with the line number
from the input file the match was found on
• ‘-H’
– Prefix each line of output with the input file name
that the match was found in
• ‘-T’
– Makes sure that the actual line content (or
whatever content comes after the ‘-T’) lands on a
tab stop
Examples using ‘-H’, ’-n’, and ‘-T’
• ‘-A num’
– Print num lines of trailing context after matching
lines
• ‘-B num’
– Print num lines of leading context before
matching lines
• ‘-C num’ or ‘-num’
– Print num lines of leading and trailing output
context
Examples using ‘-A’, ’-B’, and ‘-C’
• ‘-G’
– Interpret pattern as basic regular expression
(BRE). This is the default.
• ‘-E’
– Interpret pattern as extended regular expression
(ERE)
• When using basic regular expression some
special characters (like ‘?’ in the previous
example) loose their special meaning and
must have a ‘\’, the escape character, before
BRE and ERE Difference
67
Introduction
AWK is a great language. Awk is geared
towards text processing and report
generation, yet features many
well-designed features that allow for
serious programming. And, unlike some
languages, awk's syntax is familiar, and
borrows some of the best parts of
AWK Programming languages like C, python, and bash
(although, technically, awk was created
before both python and bash). Awk is
one of those languages that, once
learned, will become a key part of one’s
strategic coding arsenal.
Awk stands for the names of its authors
“Aho, Weinberger, and Kernighan”
SYNTAX
[Note: Either search pattern or action(s) are optional, but not both.]
THE first awk
Explanation • Space is considered as the default OFS i.e. Output Field Separator.
• The following command won’t retrieve the kth column of the CSV file.
Note/Remarks • awk '{print $k}' input_csv_file
Printing Multiple fields
of specially delimited files
• Printing multiple columns of files with delimiters
Purpose other than space, say comma. Files having comma as
the delimiter are called CSV files.
NR
FS
OFS
Awk also allows the use of boolean operators "||" (for "logical or") and "&&"(for
"logical and") to allow the creation of more complex boolean expressions:
( $1 == "foo" ) && ( $2 == "bar" ) { print }
This example will print only those lines where field one equals foo and field two
equals bar.
NUMERIC variables
(find number of blank lines in a file)
So far, we've either printed strings, the entire line, or specific fields. However,
awk also allows us to perform both integer and floating point math. Using
mathematical expressions, it's very easy to write a script that counts the
number of blank lines in a file. Here's one that does just that:
BEGIN { x=0 }
/^$/ { x=x+1 }
END { print "I found " x " blank lines. :)" }
In the BEGIN block, we initialize our integer variable x to zero. Then, each time
awk encounters a blank line, awk will execute the x=x+1 statement,
incrementing x. After all the lines have been processed, the END block will
execute, and awk will print out a final summary, specifying the number of blank
lines it found.
Plenty of operators
Another nice thing about awk is its full package of mathematical operators. In
addition to standard addition, subtraction, multiplication, and division, awk
allows us to use the exponent operator "^", the modulo (remainder) operator
"%", and a bunch of other handy assignment operators borrowed from C.
These include pre- and post-increment/decrement ( i++, --foo ),
add/sub/mult/div assign operators ( a+=3, b*=2, c/=2.2, d-=6.2 ). But that's not
all -- we also get handy modulo/exponent assign ops as well ( a^=2, b%=4 ).
Looping:
• Index(search,string)
• length(string)
• split(string,array,separator)
• substr(string,position)
• substr(string,position,max)
• tolower(string)
• toUpper(string)
Report generation using awk
awk –F”,”
'BEGIN {print "EmpID\tQualification\tInstitute";}
{print $1,"\t",$2,"\t",$3;}
END{print "REPORT GENERATED.\n";}'
list1.txt
THANK YOU
83