Posts

Showing posts with the label bash

Zero padded integer in BASH

Let say we are trying to print 01 We can do that, using the following command i=1 a=`printf "%0*d\n" 2 $i` If we echo the ${a} variable, we will see the desired formatted integer i.e. 01

Get the nth positional argument in bash?

Positional argument can be obtained in bash by creating the following file #!/bin/bash n=2 echo ${!n} Running that file in the following way:  ./file.sh sun mon tue wed will print mon The next one also gives the same result  eval echo \${$n}

Log out open remote SSH session

Kill forgotten ssh login pkill -9 -t pts/0

Bash Shell Scripting for file handling

Add two single column file side by side Of same length   awk 'NR==FNR{_[NR]=$0;next}{print $1,$2,_[FNR]}' file2 file1 Of different length awk 'NR==FNR { a[c=FNR]=$0; next }{ printf "%-8s \t %s\n", a[FNR], $0 } END { for(i=FNR+1;i<=c;i++) print a[i] }' file2 file1 Cut n-th column of a file to separate file   awk < infile '{print $n}' > outfile

Copy single file in multiple folder using bash shell

Recursive copy echo folder1 folder2 folder3 | xargs -n 1 cp -f file or echo folder*/ | xargs -n 1 cp -f file

Playing with shell!

Playing with shell Here I have summarized few shell script which I routinely use. All the informations are floating in the net. It needs just a little bit of careful google search and then test by yourself. Start with a simple one: Addition, subtraction, multiplication and division  Let say a=10, b=5, c=a+b or a-b or a/b or a*b. How to do that using Bash (Born Again Shell) shell scripting? However, bash script will give result in integer number.    a=10 b=5 c=$(($a+$b)) echo $c It will print 15. c=$(($a-$b)) echo $c It will print 5. c=$(($a/$b)) echo $c It will print 2.   c=$(($a*$b)) echo $c It will print 50. Let say you would like to do little complex calculation like  c=(a+b)/a*10 - b/(a-100)   c=$(($(($a+$b))/$(($a*10))-$(($b/$(($a-100)))))) What if one needs to get the same operation for real numbers? One needs to use then awk script. a=10.5 b=2.5 c=$(echo $a $b | awk '{ pr...