Saturday, May 24, 2014

Unix Shell Command Substitution(2)

1. Self-made head command
./script_1:
 #! /bin/bash  
 #remove the "-" in the very beginning and leave the number here  
 number=$(echo $1 | sed -e 's/^-//')  

 #remove the first positional parameter  
 shift  

 #option q means "exit code", sed will read first "number" lines of   
 #text, do nothing, output, and quit (if with -n, suppressing the   
 #output of each pattern space, nothing get output and then quit)  
 #So following command means, output first number lines of text of  
 #file $1  
 sed ${number}q $1  

terminal:
 aubinxia@aubinxia-fastdev:~/Desktop/xxdev$ ./script_1 -2 ./text  
 Hello  
 Hello world  
 aubinxia@aubinxia-fastdev:~/Desktop/xxdev$ ./script_1 -3 ./text  
 Hello  
 Hello world  
 Hello amazing world!  

2. Example of Command Substitution
./text:
 xx:/California/Los Angeles  
 yy:  
 zz:  

./script_1:
 #! /bin/bash  

 #note: how while condition works:  
 #read user address and detect if there is more string to read  
 #if yes, then while condition is true, it will proceed to run  
 #the loop body, if no, quit.  
 #So the point is: if the last line doesn't end up with new line  
 #operator, after reading user and address, it will detect that   
 #there is no more string to read, then it quit, so the last line  
 #doesn't get processed!  
 #So, for the input file, the last line must end up with new line  
 #operator.  

 #firstly remove all mail_list file to clear up all existing records  
 rm *.mail_list  

 #the shell read user and address from the ./text file, and use command  
 #substitution to transform the address to part of file name  
 #lastly append the user name to generated file  
 cat ./text | \  
 while IFS=":" read user address  
 do  
   path=${address:-/New York/New York City}  
   file=./$(echo $path | sed -e 's/^\///' -e 's/ /_/g' -e 's/\//-/g').mail_list  
   echo $user >> $file  
 done  


terminal:
 aubinxia@aubinxia-fastdev:~/Desktop/xxdev$ ./script_1  
 aubinxia@aubinxia-fastdev:~/Desktop/xxdev$ cat ./California-Los_Angeles.mail_list  
 xx  
 aubinxia@aubinxia-fastdev:~/Desktop/xxdev$ cat ./New_York-New_York_City.mail_list  
 yy  
 zz  

3. expr command:
Mainly used on arithmetic calculations:
The reason to escape '*' is: shell may take it as wildcard
If using double quote(last command), then it will be taken as string
expr will output the result
 aubinxia@aubinxia-fastdev:~/Desktop/xxdev$ expr 5 + 2  
 7  
 aubinxia@aubinxia-fastdev:~/Desktop/xxdev$ expr 5 - 2  
 3  
 aubinxia@aubinxia-fastdev:~/Desktop/xxdev$ expr 5 * 2  
 expr: syntax error  
 aubinxia@aubinxia-fastdev:~/Desktop/xxdev$ expr 5 \* 2  
 10  
 aubinxia@aubinxia-fastdev:~/Desktop/xxdev$ expr 5 / 2  
 2  
 aubinxia@aubinxia-fastdev:~/Desktop/xxdev$ expr "5 + 2"  
 5 + 2  

No comments:

Post a Comment