I have a text file for which i need a script which does some fancy search and replace.
Basically i want to loop through each line, if i find an occurance of certain string format then i want to carry on search on replace another line, once i replaced this line i will contine to search for the previous string format once i find it i will again replace the next line with a specific format.
Eg
CODE A_123
TEXT
TEXT
VAL 1,2,3
TEXT
CODE A_321
TEXT
TEXT
VAL 1,2,3XT
In this example i want to say find CODE A*, if i find this look for VAL* and replace with X. Continue doing this for the whole file
while read -r line
do
case "$line" in
"CODE A"*) flag=1;;
esac
if [ "$flag" -eq 1 ];then
case "$line" in
VAL* ) echo "VAL 5,6,7";flag=0;continue;;
* ) echo $line;;
esac
fi
[ "$flag" -eq 0 ] && echo $line
done <"file"
output
$ more file
CODE A_123
TEXT
TEXT
VAL 1,2,3
TEXT
CODE A_321
TEXT
TEXT
VAL 1,2,3
TEXT
TEXT
VAL 1,2,3
TEXT
END
CODE A_321
TEXT
TEXT
VAL 1,2,3
$ ./shell.sh
CODE A_123
TEXT
TEXT
VAL 5,6,7
TEXT
CODE A_321
TEXT
TEXT
VAL 5,6,7
TEXT
TEXT
VAL 1,2,3
TEXT
END
CODE A_321
TEXT
TEXT
VAL 5,6,7
If the input becomes large that may become slow. If so, post again here and we can talk about using sed, awk, or perl to accomplish this instead. (All three can do it and in less lines of code in most cases.)
while(<DATA>){
$flag=1 if /^CODE.*/;
if(/^VAL.*/){
$flag=0;
$_="X\n";
}
print;
}
__DATA__
CODE A_123
TEXT
TEXT
VAL 1,2,3
TEXT
CODE A_321
TEXT
TEXT
VAL 1,2,3XT