Linux Labs

Bash: text processing and scripts / Stage 2 of 9

sed and awk: editing and fields of a stream

Not running Starting usually ~20 s
Leave the lesson

Step 3 of 9 · on a machine · 6 min

Editing in place

The replacement is ready — now it has to go into thirty files in a way you can roll back.

The -i option writes the result back into the file and prints nothing on the screen. With a suffix, -i.bak, sed first saves the original next to it — site-01.conf.bak — so it can be restored after a mistake. sed takes as many files as you like: site-*.conf is a filename pattern that the shell expands into thirty names.

Check yourself 1 question

You ran sed -i.bak '/^timeout=/s/30/60/' site-*.conf, then ran the same command again by mistake. What is on the timeout= line of site-01.conf.bak now?

  • The second run saved the already fixed file to .bak and wrote over the earlier copy: cat site-01.conf.bak shows timeout=60.

  • The second run found no 30 on the line — it already says 60 — and replaced nothing. The file and the copy both have timeout=60.

  • The copy is there, but the second run overwrote it: it now has timeout=60.

Every -i.bak run puts whatever the file holds right now into the copy. The second run saved the already fixed file, and the original with timeout=30 is gone. That is why an in-place edit is run once, and the copy is checked before any repeat.

An in-place edit is checked outside sed. grep -h '^timeout=' site-*.conf | sort | uniq -c gathers the line from every file into one table: -h drops the file name from the start of each line, and identical lines merge into one with a count. diff shows how the file differs from the copy: diff site-01.conf.bak site-01.conf prints the old line marked < and the new one marked >.

Exercise · do it

Move the backend in every config

In ~/sed-lab/conf, move the backend of every site-*.conf to 10.0.0.9:8080. The rollback lines must stay as they were, and every file needs a .bak copy of the original.

Sign in and start The machine is available after signing in

Goals · 0 of 2

  • Point the backend= lines to the new address without touching the rollback lines not done yet
  • Keep the original of every file in .bak not done yet

Step goals

0 of 2
  • Point the backend= lines to the new address without touching the rollback lines — not done yet
  • Keep the original of every file in .bak — not done yet
Ubuntu 24.04

Step goals

0 of 2
  • Point the backend= lines to the new address without touching the rollback lines — not done yet
  • Keep the original of every file in .bak — not done yet
Loading…