Read, edit, and find text

Synopsis

Save two lines in a text file, search them, and find the file from its parent directory. Use the practice directory from Files, paths, and directories and an ordinary account with the vi editor and the more viewer installed.

Open a field note

Enter the practice directory and check the destination.

Shell input
cd "$HOME/unix-practice"
pwd
ls notes

Use notes/meadow-log.txt for a new practice note. If that name already contains a previous exercise, inspect the file before modifying it. Start the editor.

Shell input
vi notes/meadow-log.txt

The editor takes over the terminal. Tildes at the left edge mark screen rows beyond the end of the file. The shell waits in the background until the editor exits.

Write and save two lines

The editor starts in command mode. Press the lowercase letter i to enter insert mode. Type the following two lines, pressing Enter between them.

File contents · notes/meadow-log.txt

morning: north meadow
evening: south pond

Press Esc to return to command mode. Type :wq and press Enter. The colon opens the editor’s command line. The w command writes the file, and q quits. The shell prompt returns.

If the text appears in the wrong place, press Esc, type :q!, and press Enter. The editor discards the changes made since the last write. Reopen the file and try again. OpenBSD vi(1)

Read the saved file

Print the file to the terminal.

Shell input
cat notes/meadow-log.txt

Check the spelling and the line break against the two lines above. To correct a saved word, reopen the file in vi, move the cursor onto the word, type cw, and enter the replacement. Press Esc, then type :wq and press Enter.

Open the same note in a page viewer.

Shell input
more notes/meadow-log.txt

A short file may fit on a single screen and return immediately to the shell. If the viewer pauses, press the space bar for the next screen or q to leave. On a longer file, type /meadow and press Enter to search forward.

Search contents and filenames

Find lines containing the word pond and include their line numbers.

Shell input
grep -n 'pond' notes/meadow-log.txt

Expected output

2:evening: south pond

Here grep examines the file’s contents. To search directory entries by name, give find a starting directory and a filename pattern.

Shell input
find . -name '*-log.txt'

Look for ./notes/meadow-log.txt. The quotes pass the asterisk to find, which applies the pattern in each directory it visits. If the search returns nothing, run pwd. A search beginning at . can only reach files under the current directory.

Continue with Users, groups, and permissions.

UNIX is a registered trademark of The Open Group.