path=!echo $PATH

print path

path[0].split(":")

print len(path[0].split(":"))

"""
Explanation: Let's play iPython and BASH a bit
count number of paths in $PATH:
End of explanation
"""


!echo $PATH|tr ":" " "|wc -w

"""
Explanation: which is the same as the following command in BASH shell:
End of explanation
"""


!locale

!export LANG='en_US.UTF-8'

!locale

"""
Explanation: change the language environment
End of explanation
"""


!ls -ld /etc/p*

!ls -ld /etc/p* | wc -l

!ls -ld /etc/p????

!ls -ld /etc/p???? | wc -l

!ls -ld /etc/p[aeiou]*

!ls -ld /etc/p[aeiou]* | wc -l

!ls -ld /etc/p[!aeiou]*

!ls -ld /etc/p[^aeiou]*

"""
Explanation: look for files:
the flag -ld of "ls" means "list directory".
End of explanation
"""


!touch d{m,n,o}t

!ls

"""
Explanation: where [!aeiou] means: not a or e or i or u.
Indeed,in this case, regular expressoin  [^aeiou] also works.
End of explanation
"""


import re

!wget http://linux.vbird.org/linux_basic/0330regularex/regular_express.txt

!cat -n regular_express.txt

!cat regular_express.txt |wc -l

!grep -n 'the' regular_express.txt

"""
Explanation: regular expression
End of explanation
"""


pattern = re.compile('the')

for line in open("regular_express.txt", "r"):
    if pattern.search(line) is not None:
        print line

!grep -nv 'the' regular_express.txt

!grep -ni 'the' regular_express.txt

!grep -n 'air' regular_express.txt

!grep -ni 't[ae]st' regular_express.txt

!grep -n 't[ae]st' regular_express.txt

!grep -n '[^g]oo' regular_express.txt

!grep -n '[[:digit:]]' regular_express.txt

!grep -n '[[:lower:]]' regular_express.txt

"""
Explanation: the above BASH command is the same as the following code in Python:
End of explanation
"""


!grep -n '^[^A-Za-z]' regular_express.txt

"""
Explanation: get the line which is not started by any capital or lower-case alphabets:
End of explanation
"""


!grep -n '!$' regular_express.txt

"""
Explanation: get the line which is ended by '!':
End of explanation
"""


!grep -n '.$' regular_express.txt

!grep -n 's.c' regular_express.txt

!grep -n 's[a-zA-Z]c' regular_express.txt

!grep -n 'oo' regular_express.txt

!grep -n 'ooo*' regular_express.txt

!grep -n 'g*g' regular_express.txt

"""
Explanation: get the line which is ended by '.'   :
End of explanation
"""


!grep -nE 'goo+g' regular_express.txt

!ps -el |grep -E '^[0-9]+ R'

"""
Explanation: using 'ooo*' will lead to the same result as using 'oo'
End of explanation
"""


!dpkg -L iproute2 | grep -E '/bin|/sbin'

!dpkg -L iproute2 | grep -E '/bin|/sbin' | wc -l

!dpkg -L iproute2 | grep -E '/s?bin' | wc -l

"""
Explanation: -E flag has to be added if one want to use expressions such as + or |.
End of explanation
"""


f=open("regular_express.txt", "r")
file=f.read()

print repr(file)

for line in open("regular_express.txt", "r"):
    print line

os.mkdir("tmp")

os.listdir(os.getcwd())

ls

os.removedirs("tmp")

os.listdir(".")

"""
Explanation: Remark
?: showing once or 0 times
*: showing for any times (including 0 times)
+: showing at least once
Remark:
-i, --ignore-case
-v  --invert-match
-n, --line-number
-E: extended
End of explanation
"""


for root,dirs,files in os.walk(os.getcwd()):
    print root,dirs,files
    print

for root, dirs, files in os.walk(os.getcwd()):
    for file in files:
        print os.path.join(root,file)

for root, dirs, files in os.walk(os.getcwd()):
    for file in files:
        if file.endswith('.txt'):
            print file

!whereis regex

!find / -name 'ifconfig'

!find -type f -user chweng -name '*.txt'

!find -type d -user chweng -name '0*'

!sudo fdisk -l | grep -nE "^Disk /dev/[hs]d"

sudo find /etc -type f | wc -l

du -hl /etc/

"""
Explanation: learn a bit of os.walk():
End of explanation
"""


!ps -el

"""
Explanation: bash
chweng@chweng-VirtualBox:~$ jobs
[1]+  Running                 sleep 100 &amp;
chweng@chweng-VirtualBox:~$ fg 1  # move process 1 to the foreground
sleep 100
then, we can press ctrl+z, which will move the process to the background and pause it.
then, type "bg 1" in order to start it again in the background
process
flags: 
-e:all processes
-l:state
-f: also print UID(user ID) and PPID(parent process ID)
End of explanation
"""


%%bash
var=12345
echo "The length of var1=$var is ${#var}."

%%bash

set $(eval du -sh ~$user);dir_sz=$1
echo "$1,$2"
echo "${dir_sz}"

echo ""

set $(eval df -h|grep " /$");fs_sz=$2
echo "$1,$2"
echo "${fs_sz}"

%%bash

set $(eval du -sh ~$user);dir_sz=$1
set $(eval df -h|grep " /$");fs_sz=$2
echo "Size of my home directory is ${dir_sz}."
echo "Size of my file system size is ${fs_sz}."

"""
Explanation: the "top" command
http://mugurel.sumanariu.ro/linux/the-difference-among-virt-res-and-shr-in-top-output/

RES stands for the resident size, which is an accurate representation of how much actual physical memory a process is consuming. (This also corresponds directly to the %MEM column.) This will virtually always be less than the VIRT size, since most programs depend on the C library.
SHR indicates how much of the VIRT size is actually sharable (memory or libraries). In the case of libraries, it does not necessarily mean that the entire library is resident. For example, if a program only uses a few functions in a library, the whole library is mapped and will be counted in VIRT and SHR, but only the parts of the library file containing the functions being used will actually be loaded in and be counted under RES.

use "top -o RES" to sort by resident size(RES)
16.11.2016
The following cell is the content of the script testPS.sh:
```BASH
!/bin/bash
ps -f
read
```
Now, we execute it:
```BASH
chweng@chweng-VirtualBox:~/code/exercises$ ./testPS.sh 
UID        PID  PPID  C STIME TTY          TIME CMD
chweng    9960  2374  0 16:26 pts/31   00:00:00 bash
chweng    9974  9960  0 16:26 pts/31   00:00:00 /bin/bash ./testPS.sh
chweng    9975  9974  0 16:26 pts/31   00:00:00 ps -f
chweng@chweng-VirtualBox:~/code/exercises$ source testPS.sh 
UID        PID  PPID  C STIME TTY          TIME CMD
chweng    9960  2374  0 16:26 pts/31   00:00:00 bash
chweng    9980  9960  0 16:26 pts/31   00:00:00 ps -f
```
```BASH
chweng@chweng-VirtualBox:~$ var1=1111
chweng@chweng-VirtualBox:~$ var2=3333
chweng@chweng-VirtualBox:~$ echo "${var1}222"
1111222
chweng@chweng-VirtualBox:~$ set | grep "var1"
var1=1111
chweng@chweng-VirtualBox:~$ set | grep "var2"
var2=3333
```
BASH
chweng@chweng-VirtualBox:$ export var1
chweng@chweng-VirtualBox:$ bash
chweng@chweng-VirtualBox:$ echo $var1
1111
chweng@chweng-VirtualBox:$ echo $var2
Some examples that uses BASH variables:
End of explanation
"""


%%bash

:
echo "exit status=$?"

%%bash

ls /dhuoewyr242q
echo "exit status=$?"

%%bash

true
echo "exit status=$?"

%%bash

false
echo "exit status=$?"

%%bash

value=123
test $value=="123"
echo "exit status=$?"
echo""
test $value=="456"
echo "exit status=$?"

"""
Explanation: In BASH, a line is excuted successfully if the exit status is 0.
End of explanation
"""


%%bash

value=123
test $value == "123"
echo "exit status=$?"
echo""
test $value == "456"
echo "exit status=$?"

"""
Explanation: The above result is wrong. it's necessary to wrap == with SPACES, as the follows:
End of explanation
"""


%%bash
help [

%%bash

value=123
[ $value == "123" ]
echo "exit status=$?"
echo""
[ $value == "456" ]
echo "exit status=$?"

%%bash

/usr/bin/[ 0 == 1 ]
echo "exit status=$?"

"""
Explanation: the command test can be replaced by its synonym [ ]:
End of explanation
"""


%%bash

#!/bin/bash
# using [ and [[

file=/etc/passwd

if [[ -e $file ]]
then
        echo "Password file exists."
fi

# [[ Octal and hexadecimal evaluation ]]
# Thank you, Moritz Gronbach, for pointing this out.

decimal=15
octal=017       # = 15 (decimal)
hex=0x0f        # = 15 (decimal)

if [ "$decimal" -eq "$octal" ]
then
        echo "$decimal equals $octal"
else
        echo "$decimal is not equal to $octal" # 15 is not equal to 017
fi      # Doesn't evaluate within [ single brackets ]!

if [[ "$decimal" -eq "$octal" ]]
then
        echo "$decimal equals $octal" # 15 equals 017
else
        echo "$decimal is not equal to $octal"
fi      # Evaluates within [[ double brackets ]]!

if [[ "$decimal" -eq "$hex" ]]
then
        echo "$decimal equals $hex" # 15 equals 0x0f
else
        echo "$decimal is not equal to $hex"
fi      # [[ $hexadecimal ]] also evaluates!

"""
Explanation: example: ex4-4.sh:
use the advanced-test:[[]]
to compare different integer strings in different forms (it could be that one in decimal and another in octal format)
End of explanation
"""


!mkdir /home/chweng/a

!touch /home/chweng/a/123.txt

%%bash
#!/bin/bash
# using file test operator

DEST="~/b"
SRC="~/a"

# Make sure backup dir exits
if [ ! -d $DEST ]
then
        mkdir -p $DEST
fi

# If source directory does not exits, die...
if [ ! -d $SRC ]
then
        echo "$SRC directory not found. Cannot make backup to $DEST"
        exit 1
fi

# Okay, dump backup using tar
echo "Backup directory $DEST..."
echo "Source directory $SRC..."
/bin/tar -Jcf $DEST/backup.tar.xz $SRC 2>/dev/null

# Find out if backup failed or not
if [ $? -eq 0 ] 
then
        echo "Backup done!"
else
        echo "Backup failed"
fi

"""
Explanation: example: ex4-4.sh:
End of explanation
"""


%%bash
i=5
if [ $i -ge 0 ];then echo "$i >= 0";fi

"""
Explanation: See if an integer A is greater equal than another integer B:
End of explanation
"""


%%bash
i=5
if (($i >= 0));then echo "$i >= 0";fi

%%bash
i=5
if [ $i >= 0 ];then echo "$i >= 0";fi

%%bash
i=05
if [ $i -ge 0 ];then echo "$i >= 0";fi

"""
Explanation: alternatively, one can write it like this (with the help of )
End of explanation
"""


%%bash
echo $((7**2))

%%bash
echo $((7%3))

%%bash
#!/bin/bash
# calculate the available % of disk space

echo "Current Mount Points:"
mount | grep -E 'ext[234]|xfs' | cut -f 3 -d ' ' 

#read -p "Enter a Mount Point: " mntpnt
mntpnt="/home"

sizekb=$(df $mntpnt | tail -1 | tr -s ' ' | cut -f 2 -d ' ')
availkb=$(df $mntpnt | tail -1 | tr -s ' ' | cut -f 4 -d ' ')

availpct=$(echo "scale=4; $availkb/$sizekb * 100" | bc)

printf "There is %5.2f%% available in %s\n" $availpct $mntpnt

exit 0

"""
Explanation: arithmatic calculations are enclosed by (()):
End of explanation
"""


%%bash
#!/bin/bash
# calculate the available % of disk space

echo "Current Mount Points:"
mount | egrep 'ext[234]|xfs' | cut -f 3 -d ' ' # -f: field; -d:delimiter

#read -p "Enter a Mount Point: " mntpnt
mntpnt="/home"

df_out="$(df $mntpnt | tail -1)"

set $df_out

availpct=$(echo "scale=4; ${4}/${2} * 100" | bc)

printf "There is %5.2f%% available in %s\n" $availpct $mntpnt

exit 0

%%bash

#!/bin/bash
# shift left is double, shift right is half

declare -i number

#read -p "Enter a number: " number
number=-4

echo " Double $number is: $((number << 1))"
echo " Half of $number is: $((number >> 1))"

exit 0

"""
Explanation: Another code which do exactly the same thing:
End of explanation
"""


%%bash

#!/bin/bash
# declare constants variables

readonly DATA=/home/sales/data/feb09.dat
echo $DATA
echo

DATA=/tmp/foo
# Error ... readonly variable

echo $DATA

exit 0

"""
Explanation: therefore, it is arithmatic shift in the above script.
17112016
local variables can be declared as readonly
End of explanation
"""


%%bash
#!/bin/bash
# Testing ranges of characters.

Keypress=5

#echo; echo "Hit a key, then hit return."
#read Keypress

case "$Keypress" in
        [[:lower:]]     ) echo "Lowercase letter";;
        [[:upper:]]     ) echo "Uppercase letter";;
        [0-9]           ) echo "Digit";;
        *                       ) echo "Punctuation, whitespace, or other";;
esac    # Allows ranges of characters in [square brackets],
                #+ or POSIX ranges in [[double square brackets.

%%bash
#!/bin/bash
# menu case

echo -n "

        Menu of available commands: 
        =================================
        1. full directory listing
        2. display current directory name
        3. display the date
                  
                   q. quit                 
        =================================
        Select a number from the list:  "
        #read  answer
        answer=2

case "$answer" in
        q*|exit|bye ) echo "Quitting!" ; exit ;;
        1) echo "The contents of the current directory:"
                ls -al ;;
        2) echo "The name of the current directory is $(pwd)" ;;
        3) echo -n "The current date is: " 
                date +%m/%d/%Y ;;
        *) echo "Only choices 1, 2, 3 or q are valid" ;;
esac

exit

"""
Explanation: switch case
End of explanation
"""


for planet in "Mercury 36" "Venus 67" "Earth 93" "Mars 142" "Jupiter 483"

%%bash
#!/bin/bash
# Planets revisited.
# Associate the name of each planet with its distance from the sun.

for planet in "Mercury 36" "Venus 67" "Earth 93" "Mars 142" "Jupiter 483"
do
        set -- $planet  # Parses variable "planet"
                                        #+ and sets positional parameters.
        # The "--" prevents nasty surprises if $planet is null or
        #+ begins with a dash.

# May need to save original positional parameters,
#+ since they get overwritten.
# One way of doing this is to use an array,
# original_params=("$@")

        echo "$1                $2,000,000 miles from the sun"
        #-------two tabs---concatenate zeroes onto parameter $2
done

# (Thanks, S.C., for additional clarification.)

exit 0

"""
Explanation: in the above example, \$(pwd) can be replaced by $PWD if the env variable PWD exists
the "for each" loop
End of explanation
"""


%%bash
#!/bin/bash

#echo $1
#file=$1

cd /home/chweng/code/exercises/
file="hello.sh"
 
if [ -f $file ]
then
  echo "the file $file exists"
fi 

for((j=1;j<=5;j++))
do
  echo $j, "Hello World"
done

"""
Explanation: another way to create a loop, as what people normally do in Java:
End of explanation
"""


%%bash
#!/bin/bash

#echo $1
#file=$1

cd /home/chweng/code/exercises/
file="hello.sh"
 
if [[ -f $file && true ]]
then
  echo "the file $file exists"
fi 

for((j=1;j<=5;j++))
do
  echo $j, "Hello World"
done

"""
Explanation: review: when to use the enhanced-test [[ ]]? 
A: when && or || operator is used
End of explanation
"""


%%bash

#!/bin/bash
# increment number

# set n to 1
n=1

# continue until $n equals 5
while [ $n -le 5 ] 
do
        echo "Welcome $n times."
        n=$(( n+1 )) # increments $n
done


%%bash

#!/bin/bash
# increment number

# set n to 1
n=1

# continue until $n equals 5
while (( n <= 5 )) 
do
        echo "Welcome $n times."
        (( n++ )) # increments $n
done

%%bash
#!/bin/bash
# while can read data

ls -al | while read perms links owner group size mon day time file
do
        [[ "$perms" != "total" && $size -gt 100 ]] && echo "$file       $size"
done

exit

"""
Explanation: while loop:
End of explanation
"""


%%bash
#!/bin/bash
# break, continue usage

LIMIT=19        # Upper limit

echo
echo "Printing Numbers 1 through 20 (but not 3 and 11)."

a=0

while (( a <= LIMIT))
do
        ((a++))
   
        if [[ "$a" -eq 3  ||  "$a" -eq 11 ]] # Excludes 3 and 11.
        then
                continue        # Skip rest of this particular loop iteration.
        fi

        echo -n "$a " # This will not execute for 3 and 11.
done

# Exercise:
# Why does the loop print up to 20?

echo; echo

echo Printing Numbers 1 through 20, but something happens after 2.

##################################################################
# Same loop, but substituting 'break' for 'continue'.

a=0

while [ "$a" -le "$LIMIT" ]
do
        a=$(($a+1))

        if [ "$a" -gt 2 ] 
        then
                break # Skip entire rest of loop.
        fi

        echo -n "$a "
done
exit 0

%%bash
#!/bin/bash
# The "continue N" command, continuing at the Nth level loop.

for outer in I II III IV V # outer loop
do
        echo; echo -n "Group $outer: "
   
        # --------------------------------------------------------------------
        for inner in 1 2 3 4 5 6 7 8 9 10 # inner loop
        do
                if [[ "$inner" -eq 7 && "$outer" = "III" ]]
                then
                        continue 2      # Continue at loop on 2nd level, that is "outer loop".
                                                # Replace above line with a simple "continue"
                                                # to see normal loop behavior.
                fi

                echo -n "$inner " # 7 8 9 10 will not echo on "Group III."
        done
        # --------------------------------------------------------------------
done

echo; echo

exit 0


%%bash
#!/bin/bash
# The "continue N" command, continuing at the Nth level loop.

for outer in I II III IV V # outer loop
do
        echo; echo -n "Group $outer: "
   
        # --------------------------------------------------------------------
        for inner in 1 2 3 4 5 6 7 8 9 10 # inner loop
        do
                if [[ "$inner" -eq 7 && "$outer" = "III" ]]
                then
                        break 2      # Continue at loop on 2nd level, that is "outer loop".
                                                # Replace above line with a simple "continue"
                                                # to see normal loop behavior.
                fi

                echo -n "$inner " # 7 8 9 10 will not echo on "Group III."
        done
        # --------------------------------------------------------------------
done

echo; echo

exit 0


"""
Explanation: break & continue:
End of explanation
"""


%%bash
#!/bin/bash
# Exercising functions (simple).

JUST_A_SECOND=1

funky ()
{ # This is about as simple as functions get.
        echo "This is a funky function."
        echo "Now exiting funky function."
} # Function declaration must precede call.


fun ()
{ # A somewhat more complex function.
        i=0
        REPEATS=5

        echo
        echo "And now the fun really begins."
        echo

        sleep $JUST_A_SECOND    # Hey, wait a second!
        while [ $i -lt $REPEATS ]
        do
                echo "----------FUNCTIONS---------->"
                echo "<------------ARE-------------"
                echo "<------------FUN------------>"
                echo
                ((i++))
        done
}

# Now, call the functions.

funky
fun

exit $?


"""
Explanation: function
End of explanation
"""


%%bash
#!/bin/bash
# Global and local variables inside a function.

func ()
{
        local loc_var=23                # Declared as local variable.
        echo                                    # Uses the 'local' builtin.
        echo "\"loc_var\" in function = $loc_var"
        global_var=999                  # Not declared as local.
                                                        # Therefore, defaults to global. 
        echo "\"global_var\" in function = $global_var"
}  

func

# Now, to see if local variable "loc_var" exists outside the function.

echo
echo "\"loc_var\" outside function = $loc_var"
                                      # $loc_var outside function = 
                                      # No, $loc_var not visible globally.
echo "\"global_var\" outside function = $global_var"
                                      # $global_var outside function = 999
                                      # $global_var is visible globally.
echo                                  

exit 0
#  In contrast to C, a Bash variable declared inside a function
#+ is local ONLY if declared as such.


%%bash
#!/bin/bash
# passing data to function

# DECLARE FUNCTIONS
shifter()       # function to demonstrate parameter 
                        # list management in a function
{
        echo "$# parameters passed to $0"
        while (( $# > 0 ))
        do
                echo "$*"
                shift 
        done
}

# MAIN 
#read -p "Please type a list of five words (then press Return): " varlist
varlist="i my me mine myself"

set $varlist    # this creates positional parameters in the parent

shifter $*              # call the function and pass argument list

echo "$# parameters in the parent "
echo "Parameters: $*"

exit

%%bash
#!/bin/bash
# Functions and parameters

DEFAULT=default # Default param value.

func2 () {
        if [ -z "$1" ] # Is parameter #1 zero length?
        then
                echo "-Parameter #1 is zero length.-" # Or no parameter passed.
        else
                echo "-Parameter #1 is \"$1\".-"
        fi

        variable=${1-$DEFAULT} # What does

        echo "variable = $variable"     #+ parameter substitution show?
                                                                # ---------------------------
                                                                # It distinguishes between
                                                                #+ no param and a null param.
        if [ "$2" ]
        then
                echo "-Parameter #2 is \"$2\".-"
        fi

        return 0
}

echo

echo "Nothing passed."
func2                                           # Called with no params
echo

echo "Zero-length parameter passed."
func2 ""                                        # Called with zero-length param
echo

echo "Null parameter passed."
func2 "$uninitialized_param" # Called with uninitialized param
echo

echo "One parameter passed."
func2 first                     # Called with one param
echo

echo "Two parameters passed."
func2 first second      # Called with two params
echo

echo "\"\" \"second\" passed."
func2 "" second         # Called with zero-length first parameter
echo                            # and ASCII string as a second one.

exit 0

%%bash

#!/bin/bash
# using stdout passing data

# Declare function
addup() # function to add the number to itself
{
        echo "$((numvar + numvar))"
}

# MAIN 
while : # start infinite loop
do
        clear # clear the screen
        declare -i numvar=0 # declare integer variable
   
        # read user input into variable(s)
        echo; echo
        #read -p "Please enter a number (0 = quit the script): " numvar otherwords
        numvar=100
        
        if (( numvar == 0 )) # test the user input
        then
                exit $numvar
        else
                result=$(addup) # call the function addup 
                                                # and get data from function
                echo "$numvar + $numvar = $result"
                #read -p "Press any key to continue..."
        fi
        break  # this is added by myself because I'd like to print the output in the notebook
done


"""
Explanation: bash
chweng@chweng-VirtualBox:~$ env |grep "PWD"
PWD=/home/chweng
chweng@chweng-VirtualBox:~$ 
chweng@chweng-VirtualBox:~$ cd Desktop/
chweng@chweng-VirtualBox:~/Desktop$ env |grep "PWD"
PWD=/home/chweng/Desktop
OLDPWD=/home/chweng
End of explanation
"""


!lsof / |grep "/home/chweng/.ipython"

!strace -c find /etc -name "python*"

"""
Explanation: list open files:
End of explanation
"""


!ltrace -c find /etc -name "python*"

"""
Explanation: library trace: trace library calls demanded by the specified process.
End of explanation
"""


%%bash

#Example 1: Printing the First Field of the /etc/hosts File to stdout

#cat /etc/hosts | awk '{print $1}'

#Pipes data to awk

awk '{print "field one:\t" $1}' /etc/hosts
#Uses /etc/hosts as an input file

#'{print}'                               #Prints the current record
#'{print $0}'                            #Prints the current record (more specific)
#'{print $1}'                            #Prints the first field in the current record
#'{print "field one:" $1}'               #Prints some text before field 1
#'{print "field one:\t" $1}'             #Prints some text, a tab, then field 1
#'{print "field three:" $3; print $1}'   #Prints fields on two lines in
 

!awk ' { print "" ; print $0 }' ~/code/module08

"""
Explanation: awk:
End of explanation
"""


!ls -al /home/chweng

!ls -al /home/chweng/ | awk '/^d/ {print "dir: ",$9}'

!mount |grep "ext"

!mount | awk '/ ext[234] / {print "device: ",$1,"\tmount point: " $3}'

!mount | awk '/ ext[234] / {print "device: %5s \tmount point: %5s",$1, $3}'

!ip addr show

"""
Explanation: ```bash
1. ls -al /etc | awk '$1 ~ /^d/ {print "dir: ",$9}'


ll /etc | awk '$1 ~ /^d/ && $9 !~ /^./ {print "dir: ",$9}'


ll /sbin |awk '/^-/ && $2 > 1 {print "file:",$9 "\t links: ",$2}'


cat /etc/services | awk '$1 == "ssh" {print "service: ",$1,$2}'


ss -an | awk '/^ESTAB/ && $4 ~ /:22$/ {print "ssh from:",$5}'


mount | awk '$5 ~ /ext[234]/ || $5 == "xfs" {print $3,"("$5")"}'


ps -ef | awk '$2 == 1 , $2 == 10 {print}'
```
End of explanation
"""


!ip addr show | awk '/inet / {print $2}'

!cat /etc/passwd | awk -F : '/^chweng/ {print "id:",$1," \thome:",$6}'

"""
Explanation: select ipv4's ip:
End of explanation
"""


!cat /etc/group | awk -F : '/^sudo/ {print $1 ,"users are:", $4}'

import os
os.chdir("/home/chweng/code")

"""
Explanation: bash
chweng@VirtualBox:~$ sudo fdisk -l | awk '/^Disk \/dev\/[hs]d/ {print $2,$3,$4}'
/dev/sda: 1 TiB,
End of explanation
"""


%%bash
ls -l /home/chweng/code/exercises/ |awk '/^-/ && $2 = 1 {print "file:",$9 "\t links: ",$2}'

"""
Explanation: bash
chweng@ubuntu221:~/code$ javac -d . TestDiceThrowEx1.java 
chweng@ubuntu221:~/code$ ls
RoadLog                exercises  module03  module05  module07  tw
TestDiceThrowEx1.java  module02   module04  module06  module08
chweng@ubuntu221:~/code$ java tw.loop.TestDiceThrowEx1 
diceNumber=5
Try Again.
diceNumber=5
Try Again.
diceNumber=6
Try Again.
diceNumber=6
Try Again.
diceNumber=4
Try Again.
diceNumber=5
Try Again.
diceNumber=6
Try Again.
diceNumber=2
You Win.
End of explanation
"""


!ps -ef | awk '$2 == 1 , $2 == 10 {print}'

"""
Explanation: bash
strace -c -f java tw.loop.TestDiceThrowEx1
sort:
End of explanation
"""


%%bash

echo "This is a book" | awk '
   { print "length of the string : ",$0," is : ",length($0) }'

"""
Explanation: ```bash
input data from nbafile file


awk '$3 == 82 {print $1," \t",$5}' nbafile


awk '$3 < 78' nbafile


awk '$2 ~ /c.*l/' nbafile


awk '$1 ~ /^s/ && $4 > 80 {print $1 "\t\t" $4}' nbafile
```
End of explanation
"""


