Here is a script that uses a sed
command that will do it:
filename='cars'
make='toyota'
replacement='make=nissan|model=sentra|color=green'
sed "s/^make=$make.*/$replacement/" $filename
There are a couple of problems with icarus127's answer which I have fixed and addressed here:
filename='cars'
saveIFS="$IFS"
IFS=$'\n'
# no need to call external cat, make the array at the same time the file is read
lines=($(<$filename))
# IMO, it's better and makes a difference to save and restore IFS instead of unsetting it
IFS="$saveIFS"
make='toyota'
replacement='make=nissan|model=sentra|color=green'
# the array variable MUST be quoted here or it won't work correctly
for line in "${lines[@]}"
do
# you can use Bash's regex matching to avoid repeatedly calling
# multiple external programs in a loop
if [[ $line =~ ^make=$make ]]
then
echo "$replacement"
else
echo "$line"
fi
done
However, that (and the cat
version) reads the whole file into an array, which could be a problem if it's large. It's better to use read
in a while
loop with a redirect:
filename='cars'
make='toyota'
replacement='make=nissan|model=sentra|color=green'
while read -r line
do
# you can use Bash's regex matching to avoid repeatedly calling
# multiple external programs in a loop
if [[ $line =~ ^make=$make ]]
then
echo "$replacement"
else
echo "$line"
fi
done < "$filename"