Monthly Archives: May 2017

How to …

HOW TO…

Get number of lines of a text file and assign this value to a variable

num_lines=($(wc -l ))

Ex:
Fruits.txt

Annona
Coconut
Papaya
Mango
Nuts

We have 5 lines.

num_lines=($(wc -l Fruits.txt))
echo "The number of lines in Fruits.txt is $num_lines"

The command above will print:

The number of lines in Fruits.txt is 5

Write log of a command in terminal to file

Ex:

echo "Have a nice working day!" > happy.txt

Result:
happy.txt

Have a nice working day!

Write an array to file

Ex:

arr=("Have" "a" "nice day")
printf "%s\n" "${arr[@]}" > myFile.txt

Result:
The content of myFile.txt

Have
a
nice day

Check number of arguments

Ex:

# if total arguments not equal 2
if [ $# -ne 2 ]; then               
    echo "usage: $0 Arg1 Arg2" 1>&2
    # $0 : name of script  file
    exit 1
fi

Compute time for run command

Ex:

begin=$(date +%s)

# Do something here...

end=$(date +%s)
echo "Time for running: `expr $end - $begin` s"

Get substring

Ex:

str="Have a nice day!"
sub=$(echo $str | cut -d' ' -f 1)
echo "$sub"
# explain:
# d : delimiter (space, \n, ',' ,..)
# 1 : index is marked start with 1 ...
# more information: type "man cut"

Result:

Have

Using regular expression

Ex:

str="My weight is 50.55"
pattern="[0-9][0-9][.][0-9][0-9]"

if [[ $str =~ $pattern]]; then
    echo ${BASH_REMATCH[1]}
fi

Result:

50.55

Replace a word in a string

Ex:

str="What a nice day!"
newStr=${str//What/Have}

echo "$newStr"

Result:

Have a nice day!

Push a string into a array (separate by space)

Ex:

str="What a nice day"
# Way1:
arr1=($str)
# Way2:
IFS=' ' read -a arr2 << 

echo "${arr1[@]}"

Result:

What a nice day

Get file name and its path from full path

Ex:

file="~/home/root/myfile.txt"
filename=$(basename $file)
path=${file%/*}

echo "Path: ${path}"
echo "File's name: $filename"

Result:

Path: ~/home/root
File’s name: myfile.txt

Some problems with array

Initialize an array

arr=(<element1> <element2> ...)
#===================================================
# example
arrNum=(1 2 3 4)

Access elements

${<NameOfArray>[index]}
#===================================================
# example
echo ${arrNum[1]}    # => 2

Print all elements

${<NameOfArray>[*]}    
# or 
${<NameOfArray>[@]}
#===================================================
# example
echo ${arrNum[*]}    # => 1 2 3 4

Get lengh

${#<NameOfArray>[*]} 
# or 
${#<NameOfArray>[@]}
#===================================================
# example
echo ${#arrNum[*]}    # => 4

——— Have fun! 🙂 ———