Reputation: 589
I am trying to delete lines of a file using sed but I don't want to delete these lines unless the search string matches exactly. ie.
#!/bin/bash
set -x
file="list1"
index=0
while read line ;
do
if [ ! "$line" == "@@@" ];
then
MYARRAY[$index]="$line"
#index=$(($index+1))
let index++
else
break
fi
done < $file
#echo "MYARRAY is: ${MYARRAY[*]}"
#echo "The file: ${index}"
index1=0
for i in "${MYARRAY[@]}"
do
lineNumber=$((index1 + 1))
sed -i "/${MYARRAY[$index1]}/d" "$file"
let index1++
done
sed -i "/@@@/d" "$file"
#remove empty lines
sed -i '/^$/d' "$file"
So I have a test file (list1):
line1
line2
line3
line4
line5
line6
@@@
line1_1
line2_1
And after the script has run I end up with all lines deleted because "line1" and line2" are also matching "line1_1" and "line2_1"
Any help would be appreciated!!
Upvotes: 1
Views: 1546
Reputation: 8511
If you anchor your sed pattern match to the beginning and end of the line, then it won't also match substrings. Like so:
sed -i "/^${MYARRAY[$index1]}\$/d" "$file"
(Escaping the '$' used to anchor to the end of the line since it's in a double-quoted string.)
edit: That said, it looks to me like you can replace your entire script with this one-line sed program:
sed '1,/@@@/d; /^$/d'
That deletes from the beginning of the file to the first line containing '@@@', then also deletes blank lines, and does it all in a single pass.
Upvotes: 1