Monday, October 29, 2007

Shell Script TIPS ::

--> If you have a file with Header and Trailer records (1st and last records respectively) and want to create a file without the Header and Trailer; can you use the following commands
1. rec_cnt=`cat file_with_hdr_tlr | wc -l`; rec_cnt_head=`expr $rec_cnt - 1`; rec_cnt_tail=`expr $rec_cnt_head - 1`; head -$rec_cnt_head file_with_hdr_tlr | tail -$rec_cnt_tail > file_without_hdr_tlr

2. sed '1d;$d' file_with_hdr_tlr > file_without_hdr_tlr


--> If you have to replace a character which occurs after a specific string pattern and then place the output in a new file
ex:-- 
if you have 
PATTERN_ABC=Y
PATTERN_PQR=N
PATTERN_LMN=N
PATTERN_XYZ=Y

Desired output
PATTERN_ABC=N

PATTERN_PQR=N

PATTERN_LMN=N

PATTERN_XYZ=N

Then use
cat filename  | sed "s/PATTERN_\(.*\)=Y/PATTERN_\1=N/g" > newfilename

-- courtesy my friend Majid


--> To get the decimal points after diving following can be used

1. echo "scale = 2; $var/100" | bc -l 
2. echo a | awk '{b=12345/100;print b}'­   --> [courtesy my colleague Kaushik]


--> If there is a file which is say PIPE delimited and there are fields which are blank i.e. having spaces and you want to replace those spaces with a string; say NULL (helpful when you have to insert the data into a table); use the command: sed "s/| *|/|NULL|/g"
-- courtesy my friend Majid

--> If you are using a file within your script; specify the complete path of the file. This is very important if the script is going to be used in cron.

--> One important command that can be used is 'echo $?' which will return '0' (zero) if the previous command was executed successfully. This can be used in 'if' condition.

--> The 'awk' command comes in very handy within the Shell Scripts.