Matheion

MA-CLI1 · Module 1.3

Creating and editing text files

Topics: Redirection · Terminal editors · echo

Overview

Module 1.3 — Creating and editing text files

Empty folders wait for notes. This module covers echo with > / >>, terminal editors, and verifying with cat.

By the end you should be able to: create and append text safely; open/save/quit in nano or vi; prefer an editor for mid-file edits.

Scroll Core ideas → worked examples → Quiz. Use a disposable practice directory. Plan on roughly 55–60 minutes.

Concepts

Core ideas — making and changing plain text files

Almost everything you will touch on a Unix-style system — notes, settings, scripts, logs, small tables of numbers — is stored as plain text: letters, digits, and punctuation, with no hidden formatting. Because the format is so simple, a handful of tools are enough to create and edit any of it. This module introduces the first of those tools: echo for writing a line, the symbols > and >> for steering where that line goes, and two terminal editors, nano and vi, for the moments when a single line is not enough.

Throughout, we follow Sam, who is helping run a small coastal observation project called tidewatch. Sam's sandbox is ~/cli-practice, and the project lives in ~/cli-practice/tidewatch/ with folders you already created earlier: notes/, drafts/, scripts/, archive/, and data/ (which holds raw/ and processed/).


Why text files are worth a whole module

When you are new to the terminal it is tempting to think "I will just use a normal editor window for anything involving words." That works on your own laptop, but a great deal of real work happens somewhere you cannot click: a remote machine you connected to, a build server, a tiny computer in a field station. In those places the only interface is a prompt. Being able to write down a thought, a measurement, or a reminder from that prompt, without leaving it, is a basic survival skill.

There is a second reason. Text files are what other commands consume. A later module will count lines, search through them, and move them around. Those tools are only as good as the files you give them, so it pays to learn early how to produce clean files on purpose.


echo: say a line of text

echo prints whatever you give it back to the screen, followed by a newline. That is all it does, and that simplicity is exactly why it is useful.

echo "Low tide at 06:12"

You will see Low tide at 06:12 appear and the prompt return. Nothing was saved anywhere; the words simply went to the screen, which the shell calls standard output. Quotes are not part of the message. They tell the shell "treat everything between these marks as one chunk," which matters as soon as your text includes spaces, colons, or characters that the shell would otherwise try to interpret.

If you are unsure what quote style to use, plain double quotes are a comfortable default for ordinary sentences. Single quotes are even stricter: they pass your text through untouched, which is handy when it contains dollar signs or exclamation marks.


Redirection: steering output into a file

Normally a command's output lands on the screen. Redirection lets you say "send it into a file instead." The symbol > means exactly that:

echo "Low tide at 06:12" > notes/tides.txt

Read it left to right: echo this sentence, and put the result into notes/tides.txt. Nothing appears on screen, because the output was diverted. If tides.txt did not exist, the shell creates it. You can confirm by looking inside:

cat notes/tides.txt

which prints Low tide at 06:12. cat is a quick "show me the file" command; you met it before and it will serve as our checking tool all through this module.


The sharp edge: > replaces the whole file

Here is the single most important fact in this module. When the target file already exists, a single > does not add to it. It empties it first, then writes your new text. The old contents are gone, with no warning and no trash can to rescue them.

echo "Low tide at 06:12" > notes/tides.txt
echo "High tide at 12:30" > notes/tides.txt
cat notes/tides.txt

The final cat shows only High tide at 12:30. The first line has vanished. Nothing malfunctioned; the second command did precisely what > promises. If that felt abrupt, read it once more: one greater-than sign means "make this file contain exactly this."

This is the most common way beginners lose work. You think of the line as "adding a note," your fingers type a single >, and an hour of notes becomes one line. The habit that protects you is to pause before pressing Enter on any command that contains > and ask: does this target file already hold something I care about?


Appending with >>

Two greater-than signs mean "add to the end." The existing contents stay exactly where they are, and your new line is placed after them.

echo "Low tide at 06:12" > notes/tides.txt
echo "High tide at 12:30" >> notes/tides.txt
echo "Low tide at 18:41" >> notes/tides.txt
cat notes/tides.txt

Now the file holds three lines, in the order you wrote them. Notice the pattern: the first command uses > because we are deliberately starting a fresh file, and each later command uses >> because we are growing it. If the file does not exist yet, >> quietly creates it too, so >> is never "wrong" for a first line — it is just less explicit about your intention.

A comfortable rule of thumb: when in doubt, use >>. The worst outcome is that you add a duplicate line, which you can fix. The worst outcome of a stray > is silent loss.

| You type | If file is missing | If file exists | |----------|-------------------|----------------| | echo "x" > f.txt | Creates it with one line | Replaces all contents | | echo "x" >> f.txt | Creates it with one line | Adds one line at the end |


Checking before and after

Because overwriting is silent, good habits revolve around looking. Two small checks are worth making automatic.

Before a risky write, list the folder and peek at the file:

ls notes
cat notes/tides.txt

After any write, cat the file once. Seeing the result on screen takes a second and confirms that the line is there, that it is in the right file, and that you did not accidentally clobber something. Over time this turns into a rhythm: write, show, move on.


Common confusion: "the file did not change"

Sometimes a learner runs echo "note" > notes/tides.txt and then wonders why the screen shows nothing. Remember that redirection removes the on-screen output; silence is the success signal. Another frequent slip is a typo in the path — writing to note/tides.txt instead of notes/tides.txt fails with "No such file or directory," because the folder note does not exist. Read the error message slowly; it names the exact path that failed.


One idea per line

Before moving on to editors, a word about shape. A text file is a stack of lines, and many tools treat each line as a single unit of meaning: one observation, one name, one task. When you keep one idea per line, you gain a lot for free. You can count items by counting lines, sort them, pick out the ones that mention a word, or delete a single mistaken entry without disturbing its neighbours.

Compare two ways of storing the same information. In the first, Sam writes Low 06:12, High 12:30, Low 18:41 on one line. In the second, each reading sits on its own line. The second version looks longer but is far kinder to every future command: want only the lows? Look for lines starting with Low. Want to remove a wrong reading? Delete one line. With the first version you would have to carefully carve text out of the middle of a sentence.

This is why the echo-and-append approach works so naturally: each echo produces exactly one line, and >> stacks those lines in order. Keep lines short, put a consistent label at the start, and avoid wrapping a thought across two lines.


When one line is not enough: terminal editors

Appending is perfect for adding to the end. It is useless for changing the middle: fixing a typo in line two, rewording a sentence, deleting a paragraph, rearranging three lines. For that you need an editor, a program that shows the file's contents and lets you move around and change them.

On a graphical desktop you would double-click a file. In a terminal, you type the editor's name followed by the file:

nano notes/plan.txt

The terminal screen is taken over by the editor, and your prompt disappears until you leave. This surprises many people the first time — it is not frozen, it is simply in editing mode. The two editors you will meet nearly everywhere are nano and vi (sometimes started with vim, a close relative). They solve the same problem with very different "mental models."


nano: the always-visible menu

nano behaves like most editors you already know. You open the file, you start typing, and the text appears where the cursor sits. There is no hidden mode to switch into. Along the bottom, nano prints a short menu of shortcuts, where the caret symbol ^ means the Ctrl key. So ^X means hold Ctrl and press X.

The two shortcuts you need today:

  • Ctrl+O — write Out, which means save. nano then shows the filename and asks you to confirm; press Enter.
  • Ctrl+X — eXit. If you have unsaved changes, nano asks whether to save; answer Y to save or N to throw the changes away.

A calm sequence for a first edit: open the file, type or change something, press Ctrl+O, press Enter, then press Ctrl+X. Because the menu is always on screen, you can recover from nearly any confusion by glancing at the bottom two lines.


vi: modes instead of menus

vi is older, ubiquitous, and often the only editor available on a minimal machine. Its central idea is modes. At any moment vi is in one of a few states, and the same key does different things in each.

When you open a file with vi notes/plan.txt, you start in normal mode. In this mode the keys are commands, not text. If you just start typing, you may delete lines or jump around instead of writing words. This is the number-one reason people feel trapped in vi.

To actually type text, press i (for insert). The bottom of the screen shows -- INSERT --, and now what you type goes into the file. To stop inserting and return to normal mode, press Esc. Whenever you feel lost, pressing Esc once or twice puts you back on firm ground.

To save and leave, you go from normal mode into a command line by typing a colon:

  • :wq then Enter — write the file and quit.
  • :q then Enter — quit, which only works if there are no unsaved changes.
  • :q! then Enter — quit and discard your changes. The exclamation mark means "I know, do it anyway."

The whole loop is: i → type → Esc → :wq → Enter. Practising that loop three or four times is more valuable than memorising any other vi key.


A side-by-side mental model

It helps to picture the two editors as two different kinds of rooms. nano is a room where the light is always on and the instructions are painted on the wall; you walk in and start working. vi is a workshop with a control panel: the panel has one setting for reading and commanding, another for typing, and you must switch between them deliberately.

| Task | nano | vi | |------|------|----| | Start typing | Just type | Press i first | | Stop typing | (nothing to do) | Press Esc | | Save | Ctrl+O, then Enter | :w (or part of :wq) | | Save and exit | Ctrl+O, Enter, Ctrl+X | :wq | | Exit, keep nothing | Ctrl+X, then N | :q! |

You do not need to love both. Pick one for daily use (nano is gentler to begin with) and learn only the vi escape routes so that you are never stranded when it is the only editor present.


Leaving without saving is a feature

Beginners often treat "discard changes" as a failure state. It is actually a safety valve. If you opened a file, pressed the wrong keys, and the text now looks mangled, you can leave without saving and the file on disk remains exactly as it was. In nano, that means Ctrl+X then N. In vi, that means :q!. The original file is untouched until you explicitly save, so an editor session is a safe place to experiment.


Editor or append: choosing the right tool

Both approaches produce text files, so how do you choose? Ask what kind of change you are making.

Use echo ... >> when: you are adding one short line at the end, you already know the exact text, and you do not need to see the rest of the file. A daily reading, a log-like entry, or a one-line reminder fit here. It is fast, scriptable, and leaves no screen takeover.

Use an editor when: you need to change something inside the file, write several lines at once, fix a mistake, or restructure what is already there. Anything that requires you to see surrounding text is an editor job.

Use echo ... > only when: you truly want a brand-new file, or you want to replace everything on purpose. Treat it as the "sharp tool" and reach for it deliberately.

A tidy mental summary: append to grow, edit to reshape, single-arrow to start over.


Pitfalls worth naming

  • A lone > on an existing file. Silent, immediate, unrecoverable. Prefer >> unless you mean it.
  • Typing in vi's normal mode. Characters act as commands. Press i before typing text.
  • Forgetting to save. In nano, Ctrl+X will ask; in vi, :q will refuse and warn you. Read the prompt before answering.
  • Wrong directory. echo "x" > notes.txt writes in the current directory. Run pwd if unsure where you are.
  • Mixing ideas on a line. It makes later counting and searching awkward. One note, one line.
  • Smart quotes. Pasting text from a document can bring curly quotes that the shell does not recognise as quotes. Type plain straight quotes by hand.

Self-study checklist

Tick these off in your own terminal, inside ~/cli-practice/tidewatch:

  • [ ] I can create notes/tides.txt with one line using >.
  • [ ] I can add two more lines using >> and confirm with cat.
  • [ ] I have deliberately overwritten a practice file with > and watched the earlier lines disappear.
  • [ ] I can open a file in nano, change a word, save with Ctrl+O and Enter, and exit with Ctrl+X.
  • [ ] I can open a file in vi, press i, type, press Esc, and leave with :wq.
  • [ ] I can leave vi without saving using :q!, and I know the file stayed the same.
  • [ ] I can say in one sentence when I would append and when I would open an editor.

If any box is empty, repeat that step once more before continuing. The goal is not speed; it is that your fingers know the safe path.


Summary in plain words

echo "text" shows a line; add > to put it in a file, replacing everything; add >> to put it at the end, keeping everything. When you need to change what is already inside a file, open it in nano or vi, edit, save, and exit — and remember that leaving without saving is always available. Keep each line to one idea, check results with cat, and use a practice folder so that mistakes are cheap.

Examples

Worked examples — Sam writes the tidewatch notes

Each example below is a small story. Read the scene, follow the steps (type them yourself in ~/cli-practice/tidewatch if you can), study the interpretation, and keep the takeaway. The commands are short on purpose; what matters is knowing why each one is there.


Example 1 — The first note and the first scare

Scene. It is Monday morning. Sam wants a file called tides.txt inside notes/ that records the day's readings. Nothing exists yet, and Sam wants to try the simplest route: type a line and push it into a file.

Steps.

cd ~/cli-practice/tidewatch
echo "Low tide at 06:12" > notes/tides.txt
cat notes/tides.txt

The first command moves into the project folder. The second echoes one sentence and redirects it into notes/tides.txt; the screen stays silent. The third prints the file, and Sam sees Low tide at 06:12.

A few minutes later Sam records the next reading, again with a single arrow, out of habit:

echo "High tide at 12:30" > notes/tides.txt
cat notes/tides.txt

Interpretation. The file now shows only High tide at 12:30. The earlier low-tide line is gone. Sam did nothing unusual; > always means "make the file contain exactly this." Because the file already existed, it was emptied first. No error appeared, no confirmation was asked, and there is no undo.

Takeaway. One arrow replaces; it never adds. Looking with cat right after the write is what let Sam notice the loss immediately, while the missing line was still easy to retype.


Example 2 — Growing a file safely with >>

Scene. Sam retypes the morning reading and now wants to build up a full day of entries without risking another wipe-out.

Steps.

echo "Low tide at 06:12" > notes/tides.txt
echo "High tide at 12:30" >> notes/tides.txt
echo "Low tide at 18:41" >> notes/tides.txt
echo "High tide at 00:55" >> notes/tides.txt
cat notes/tides.txt

The first line deliberately uses > because Sam wants to start a clean file — replacing the damaged one is the goal here. Every following line uses >>.

The final cat prints four lines in the order they were written:

Low tide at 06:12
High tide at 12:30
Low tide at 18:41
High tide at 00:55

Interpretation. Each echo produced exactly one line ending in a newline, and >> placed it after whatever was already there. Notice that the file never "knew" about the earlier commands; it simply kept growing at the bottom. Also notice the shape: one reading per line, each starting with a label. That shape is what makes the file easy to count, scan, and clean up later.

Takeaway. Start with > only when you intend a fresh file; after that, use >>. If Sam had used >> for the very first line too, the result would have been the same here, which shows why >> is the forgiving default.


Example 3 — Fixing a typo in the middle with nano

Scene. Looking at the file, Sam realises the third reading should say Low tide at 18:14, not 18:41; two digits were swapped. Appending cannot repair a mistake in the middle of a file, so Sam opens an editor.

Steps.

nano notes/tides.txt

The screen is replaced by nano. The four lines appear, with a menu of shortcuts along the bottom. Sam uses the arrow keys to move the cursor to the third line, presses the backspace key to remove 41, and types 14. The line now reads Low tide at 18:14.

To save, Sam presses Ctrl+O. nano shows File Name to Write: notes/tides.txt at the bottom, and Sam presses Enter to confirm. Then Ctrl+X returns to the prompt. A final check:

cat notes/tides.txt

shows all four lines, with the corrected third one.

Interpretation. Three keystrokes carried the entire save-and-leave routine: Ctrl+O to write, Enter to accept the name, Ctrl+X to exit. Had Sam pressed Ctrl+X first without saving, nano would have asked whether to save the modified buffer, and answering Y would have led to the same filename prompt.

Takeaway. Use an editor for anything inside a file. In nano, remember the trio Ctrl+O, Enter, Ctrl+X, and trust the menu at the bottom of the screen when you forget.


Example 4 — The same idea in vi, including a retreat

Scene. Sam logs into a bare machine at the field station where nano is not installed. Only vi is present. Sam wants to create a short plan file and then, as a separate exercise, practise backing out of a messy edit.

Steps — creating and saving.

vi notes/plan.txt

The screen shows an empty file and a column of tildes. Sam is in normal mode, so the first move is to press i. The bottom line reads -- INSERT --. Sam types:

Check the tide gauge
Photograph the shoreline

pressing Enter between the lines. Then Esc returns to normal mode, and Sam types :wq and presses Enter. The prompt comes back, and cat notes/plan.txt confirms both lines.

Steps — retreating. Next, Sam reopens the file with vi notes/plan.txt, presses i, and by mistake types a long, rambling paragraph. Rather than tidy it, Sam presses Esc, types :q!, and presses Enter. Running cat notes/plan.txt shows the original two lines, untouched.

Interpretation. The modes explain every step. i moves from commands to typing; Esc moves back; the colon opens a command line where wq means write and quit and q! means quit and throw away. The second session shows why leaving without saving is useful: the damaged text never reached the disk.

Takeaway. Memorise one loop for vi — i, type, Esc, :wq — and one escape — Esc, :q!. With those two, vi cannot trap you.


Example 5 — Deciding: append or edit?

Scene. By the end of the week Sam has three small jobs and must choose the right tool for each. Reading them as a set shows the decision pattern.

Job A: add tonight's reading. The text is known, and it belongs at the end of tides.txt. Sam types:

echo "Low tide at 19:20" >> notes/tides.txt

and checks with cat. No editor needed.

Job B: reword the first line of plan.txt and delete the second. Both changes sit in the middle or top of the file, and Sam needs to see the text to make them. Sam opens nano notes/plan.txt, edits, saves with Ctrl+O and Enter, and exits with Ctrl+X.

Job C: start a fresh scratch.txt that should hold only a single test line. The file may or may not exist, and Sam does not care about any old contents. Sam types:

echo "test line" > notes/scratch.txt

and recognises that the single arrow is intentional here.

Interpretation. Each job has a different shape. Appending suits a known line at the end; editing suits changes inside; the single arrow suits a deliberate fresh start. In every case Sam finished with cat to see the real result rather than assuming it.

Takeaway. Before typing, name the job in one phrase — grow, reshape, or start over — and the right tool follows. Then look at the file once to confirm.


Before you move on

Try recreating Examples 1 to 4 from memory in a fresh practice folder, without looking back at the commands. If you stall, glance at the step, then close the page and try again. The goal is for the sequences — arrow versus double arrow, Ctrl+O/Enter/Ctrl+X, i/Esc/:wq — to become automatic.

Practice check — text files

Multiple-choice check from the Matheion app lesson. Pick an answer for each question, then submit.

  1. 1.Sam's `notes/tides.txt` holds six readings. Sam runs `echo "Low tide at 19:20" > notes/tides.txt`. What does the file contain afterwards?

  2. 2.Sam wants to add a reading to the end of `notes/tides.txt` without disturbing the lines already there. Which command does that?

  3. 3.Sam opens a file with `vi` and starts typing a sentence at once. The screen jumps around and lines change in odd ways. What is the best explanation and fix?

  4. 4.In nano, Sam has finished editing and wants to save to the same file name and close the editor. Which key sequence is correct?

  5. 5.Sam made a mess in vi and wants to leave so that the file on disk stays exactly as it was before the session. Which sequence achieves this?

  6. 6.Which job is best handled by opening an editor rather than by `echo ... >>`?

  7. 7.Sam stores `Low 06:12, High 12:30, Low 18:41` on one line. Why might one reading per line serve Sam better?