Editing Text With sed
Part of the Bash Scripting section of Coddy's Terminal journey. Lesson 24 of 39.
sed edits text line by line as it passes through. Its most used command is s/old/new/, which replaces the first match on each line and prints the result. The file itself stays as it was.
sed 's/tea/coffee/' menu.txt
sed 's/tea/coffee/g' menu.txtOn the line tea and tea cake, the first command prints coffee and tea cake. The g flag replaces every match on the line, so the second prints coffee and coffee cake. Add -i to write the change back into the file instead of printing it.
sed -i '/^#/d' menu.txt
sed -n '2,4p' menu.txt/^#/d deletes every line that starts with #, because ^ means the start of a line. -n turns off the automatic printing, and 2,4p prints lines 2 to 4, so the second command shows three lines of the menu.
Challenge
MediumWrite a script that tidies a config file in place.
- Open
tidy.sh. The config file is its first argument. - With
sed -i, delete every line that starts with#. A#later in a line, as intheme=#336699, stays. - With
sed -i, replace everylocalhostwith127.0.0.1, also when a line has it twice. - Print
Tidied FILE:with the file name in place of FILE, then the whole file. - Save the file.
Try it: run bash tidy.sh app.conf. It prints:
Tidied app.conf:
host=127.0.0.1
db_url=postgres://127.0.0.1:5432/shop
allowed=127.0.0.1,127.0.0.1:3000
theme=#336699Run it a second time: the file has no comments and no localhost left, so it prints the same five lines.
Try it yourself
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Bash Scripting
1Arguments And Exit Codes
Script ArgumentsAll The ArgumentsExit CodesChecking ArgumentsRecap - Unit Converter5Text Power Tools
Finding FilesBatch Work With xargsEditing Text With sedColumns With awkRecap - Log SummaryPractice on your own: Terminal playground