We have moved to www.dataGenX.net, Keep Learning with us.

Saturday, August 17, 2013

Search the string in the file : Linux/Unix


Here, I am going to share a small shell utility which will ask source file name and the pattern which need to be searched in file and give the formatted output with the line no with line. You can select the no of lines which display before and after the string.




#!/bin/ksh
echo "enter the file name"
read V_file_name
echo "enter the string to be searched"
read V_string
line_num=`grep -n "$V_string" $V_file_name|awk -F":" '{print $1}'`
echo "The entered string occurs at the following line(s) in the file"
echo $line_num
echo "enter the required line number"
read V_req_line_num
echo "How many lines before and after the string would you like to be displayed ?"
read V_bef_aft
var_1=$(($V_bef_aft+1))
var_2=$(($V_req_line_num+$V_bef_aft))
head -$V_req_line_num $V_file_name|tail -$var_1 > req_file.txt
head -$var_2 $V_file_name|tail -$V_bef_aft >> req_file.txt
echo "The required text is....."
cat req_file.txt