Course outline
Course / The terminal and the language

Handle every line as written

Lab

How to fetch and submit this lab

Once: install the tool and connect your account.

curl -fsSL https://gonomicon.com/install.sh | sh
gonomicon login

Each lab: download it, edit the file named in the instructions, then submit.

gonomicon fetch week-1/04-06-shell-read-lines-safely
cd 04-06-shell-read-lines-safely
gonomicon submit

Go installed? gonomicon test runs the visible test on your computer first. Submitting also runs hidden checks on our server.

Goal

Read testdata/lines.txt one line at a time and print each line with a > in front of it. Every line must come out exactly as it is in the file: blank lines, spaces at the start or end, and backslashes included.

Example

If testdata/lines.txt held:

first note

    indented
C:\temp\new

your script prints:

>first note
>
>    indented
>C:\temp\new

The blank line becomes a lone >. The four spaces stay. The backslashes are not turned into anything else.

Rules

  • Edit answer.sh. It reads the file testdata/lines.txt and prints the result.
  • Use a while loop with IFS= read -r line, and feed the file in with < testdata/lines.txt after done.
  • Print each line with printf '>%s\n' and "$line" in double quotes. Do not use echo.
  • Print one output line per input line, in the original order.
  • Spaces at the start and end of a line must stay, and so must tabs. Do not trim anything.
  • Backslashes must stay exactly as written. This is what -r is for.
  • If the file is empty, print nothing at all.
  • Every line in the file ends with a newline. Do not edit testdata/lines.txt; your script only prints.
  • Do not type the sample lines into the script. The test uses different files.

What you'll practice

while with read, IFS= and -r to keep lines intact, redirecting a file into a loop, quoting "$line", and printf with %s.

Run it

gonomicon fetch week-1/04-06-shell-read-lines-safely
cd 04-06-shell-read-lines-safely
gonomicon test
gonomicon submit

Hints

  1. Read the file with a while loop and read, and feed the file in after done with < testdata/lines.txt.
  2. Plain read strips spaces at the edges and treats backslashes as special. Write while IFS= read -r line; do so each line arrives exactly as it is in the file.
  3. while IFS= read -r line; do printf '>%s\n' "$line"; done < testdata/lines.txt, written across several lines. Keep the double quotes around $line.

Something wrong with this lesson? Report a problem