Monday, 2 April 2018

Shell script to delete lines containing a pattern


#Deletes lines in a file which contains a given pattern
echo "Enter the pattern to be searched"
read p
n=$#
for i in $*
do
    if [ -f $i ]
        then   
                chk=`grep $p $i`
                if [ -z $chk ]
                then
                       echo "Pattern not found in file '$i'"
               else           
                       `grep -v $p $i > tfile`
                       echo "Before deletion"
                       cat $i
                       echo "After deletion"
                       cp tfile $i
                       cat $i
               fi
        else
               echo "File '$i' does not exist"
        fi
done




OUTPUT
csc@csc-SVE1513CYNB ~ $ sh ss.sh file2 ffff ff
Enter the pattern to be searched
Anu
Before deletion
103 Banu CIO
103 Banu CIO
103 Banu CIO
101 Anu CEO
104 Shan CFO
101 Sasha MD
After deletion
103 Banu CIO
103 Banu CIO
103 Banu CIO
104 Shan CFO
101 Sasha MD
File 'ffff' does not exist
Pattern not found in 'ff'

No comments:

Post a Comment