Reading and Editing Files

Table of Contents

  1. Printing a File: cat
  2. Scrolling Through Long Files: less
  3. The Beginning and the End: head and tail
  4. Following a File as It Grows: tail -f
  5. What Kind of File Is This? file
  6. Editing in the Terminal: nano
  7. Help, I'm Stuck in Vim
  8. Opening Files in Your Real Editor
  9. Try It Yourself

As before, everything happens in your practice folder:

cd ~/cli-practice

We need a few files with something in them. echo with > writes a line into a file (replacing what was there), and >> adds a line to the end. Chapter 6 explains both properly — for now, just run these:

echo "Buy rice" > notes/shopping.txt
echo "Buy eggs" >> notes/shopping.txt
echo "Buy coffee" >> notes/shopping.txt
seq 1 500 > notes/numbers.txt

seq 1 500 prints the numbers 1 to 500, one per line — a quick way to get a long file to practice on.

1. Printing a File: cat

cat prints the whole contents of a file to the screen:

cat notes/shopping.txt
Buy rice
Buy eggs
Buy coffee

The name comes from concatenate — joining things end to end. Give cat several files and it prints them one after another, as if they were one file:

cat notes/shopping.txt notes/todo.txt

Add -n to number the lines, which helps when an error message says something like "syntax error on line 12":

cat -n notes/shopping.txt

cat is perfect for short files. Now try it on a long one:

cat notes/numbers.txt

Five hundred lines fly past, and all you can see is the end. For long files, you need something better.

2. Scrolling Through Long Files: less

less opens a file in a viewer that lets you scroll, one screen at a time:

less notes/numbers.txt

The file now fills the terminal, and the shell prompt is gone until you leave. Inside less:

KeyWhat it does
↓ / ↑ or j / kScroll one line
Space / bScroll one page forward / back
g / GJump to the start / end of the file
/word then EnterSearch forward for word
n / NNext / previous search match
qQuit and return to the prompt

If these keys look familiar, that's because man (chapter 2) uses less to show manual pages. Learn them once and you can use both.

less is also safe: it only reads the file. Nothing you press inside it can change or delete anything. It also opens huge files — gigabytes of logs — instantly, because it only loads the part you're looking at.

3. The Beginning and the End: head and tail

Often you only care about the start or the end of a file. head shows the first 10 lines; tail shows the last 10:

head notes/numbers.txt
tail notes/numbers.txt

Use -n to choose how many lines:

head -n 3 notes/numbers.txt    # 1, 2, 3
tail -n 5 notes/numbers.txt    # 496 to 500

Where does this matter in real life?

  • head a big CSV file to see its column names without opening the whole thing.
  • tail a log file to see the most recent errors — logs are written top to bottom, so the newest lines are always at the end.

4. Following a File as It Grows: tail -f

tail -f (follow) shows the end of a file, and then keeps watching it, printing new lines the moment they're added. It's how developers watch a log while an app is running.

To see it in action, you need two terminals side by side. Open a second terminal window or tab (Cmd + T on macOS; the + button in Windows Terminal; Ctrl + Shift + T in most Linux terminals).

In the first terminal:

cd ~/cli-practice
touch notes/app.log
tail -f notes/app.log

The file is empty, so nothing appears — and the prompt doesn't come back. tail is sitting there, waiting.

In the second terminal, add some lines:

cd ~/cli-practice
echo "Server started on port 3000" >> notes/app.log
echo "GET /home 200" >> notes/app.log
echo "ERROR: database connection failed" >> notes/app.log

Each line appears in the first terminal the moment you press Enter. When you're done, go back to the first terminal and press Ctrl + C to stop following.

This is the same idea behind docker logs -f and npm run dev: a process keeps writing lines, and the terminal keeps showing them until you stop it with Ctrl + C.

5. What Kind of File Is This? file

What happens if you cat something that isn't text, like a photo or a program? Try it with any real image you have (or copy one into ~/cli-practice/photos):

cat photos/some-real-photo.jpg

You get a screen full of garbage characters, maybe some beeping, and occasionally a terminal that starts displaying text strangely afterwards. As you learned in Bits and Bytes, the bytes inside a JPEG are pixels, not letters, so printing them as text makes no sense. If your terminal gets confused, type reset and press Enter (even if you can't see what you're typing) to fix it.

To find out what's inside a file before opening it, use file:

file notes/shopping.txt
file photos/some-real-photo.jpg
notes/shopping.txt:          ASCII text
photos/some-real-photo.jpg:  JPEG image data, JFIF standard 1.01, ...

file looks at the bytes inside, not the extension. Rename a photo to .txt and file will still tell you it's a JPEG — exactly the point made in Files and File Systems.

6. Editing in the Terminal: nano

Most of the time you'll edit code in a graphical editor. But sometimes you're on a server with no desktop, or you just need to change one line in a config file, and a terminal text editor is the quickest way.

nano is the friendliest one. It's included in Ubuntu (and WSL), Git Bash, and macOS (where nano is actually a near-identical editor called pico).

nano notes/todo.txt

The file opens inside the terminal. You can type, delete, and move around with the arrow keys, like a simple text editor. At the bottom of the screen is a list of shortcuts:

^G Help    ^O Write Out    ^W Where Is    ^K Cut    ^X Exit

The ^ means Ctrl. So:

ShortcutWhat it does
Ctrl + O then EnterSave ("write out") the file
Ctrl + XExit — if there are unsaved changes, it asks whether to save (Y / N)
Ctrl + WSearch for text
Ctrl + K / Ctrl + UCut a whole line / paste it

Try it: add a line like Practise nano, press Ctrl + O, Enter, then Ctrl + X. Check it worked:

cat notes/todo.txt

If you nano a file that doesn't exist yet, nano creates it when you save. So nano notes/new-file.txt is another way to create a file.

7. Help, I'm Stuck in Vim

Sooner or later, a program will drop you into vim without warning. The most common culprit: running git commit without a message, which opens your default editor to write one — and on many systems, that default is vim.

Vim is a powerful editor that many developers love, but it works very differently: when it opens, typing doesn't insert text, and the usual shortcuts don't work. Beginners famously can't figure out how to leave. Here's the escape plan:

  1. Press Esc (maybe twice), to make sure you're in vim's command mode.
  2. Type :q! and press Enter — this means "quit, and throw away any changes".

If you actually want to keep what you typed:

  1. Press Esc.
  2. Type :wq and press Enter — "write (save), then quit".

You'll see :q! or :wq appear at the bottom of the screen as you type. That's how you know vim is listening.

If you'd rather Git opened nano instead, the Git series shows you how to change its default editor.

8. Opening Files in Your Real Editor

For real coding, you'll want a full editor like VS Code. You can open it from the terminal, right where you are:

code notes/todo.txt   # open one file
code .                # open the whole current folder as a project

code . is one of the most-used commands in web development: cd into a project, then code . to start working on it.

If you get command not found: code:

  • macOS: open VS Code, press Cmd + Shift + P, and run Shell Command: Install 'code' command in PATH.
  • WSL: install the WSL extension in VS Code on Windows; after that, code . inside WSL opens the folder in VS Code, connected to Linux.
  • Linux and Git Bash: the VS Code installer normally sets this up. Restart your terminal after installing.

Chapter 9 explains why "restart your terminal" so often fixes command not found.

9. Try It Yourself

  1. Use cat to print notes/shopping.txt, then print it again with line numbers.
  2. Open notes/numbers.txt in less. Jump to the end with G, search for 250 with /250, and quit with q.
  3. Print only lines 1 to 3 of notes/numbers.txt, then only the last line.
  4. Set up the two-terminal tail -f experiment and add three lines of your own to notes/app.log. Stop it with Ctrl + C.
  5. Run file on a text file and on a real photo. Then copy the photo, rename the copy to end in .txt, and run file on it again.
  6. Use nano to create notes/journal.txt, write two lines, save, and exit. Check it with cat.
  7. Open vim on purpose with vim notes/journal.txt, type a few random keys, then escape with Esc and :q!. Run cat to confirm nothing changed.

You can now read files of any size and make quick edits without leaving the terminal. Next comes one of the most powerful ideas on the command line: connecting commands together with pipes and redirection.

Buy Me a Coffee

Found this tutorial helpful? Consider buying me a coffee to support more free content!