sed edits text line by line. s/OLD/NEW/ changes text; -i writes the change back into the file:
learner@reef:~$ sed 's/^tea=.*/tea=2.40/' menu.conf
# menu prices
tea=2.40 ← the line that starts with tea=, all of it, changed
scone=2.80
learner@reef:~$ sed -i 's/^tea=.*/tea=2.40/' menu.conf
learner@reef:~$ cat menu.conf
# menu prices
tea=2.40 ← -i changed menu.conf itself
scone=2.80^ is the start of the line, and .* is anything, to the end of it.
Break it: > the same file
Without -i, sed only prints. Sending that back into the same file with > empties it, and nothing tells you:
A teammate wrote ~/set-open.sh to change a shop's opening time in its shop.conf. It is already runnable:
#!/bin/bash
# Usage: set-open.sh TIME FILE
sed "s/^open=.*/open=$1/" "$2" > "$2"Don't fix it yet: first see what it does, on a copy.
- Copy
~/shop.confto~/try.conf, run./set-open.sh 06:45 ~/try.conf, thencat ~/try.conf. - Say which one emptied it.
- Fix the script, so that sed changes the file itself. Copy
~/shop.confto~/try.confagain, and test it there.
Objectives
- Break it on purpose: copy
~/shop.confto~/try.conf, run the script on it, and look at it. - Say which one emptied the file.
- Fix
~/set-open.sh: it changes theopen=line in the file itself and keeps the other lines.