␡
- Starting Up the Terminal
- Getting Started
- Building Pipelines
- Running Commands as Superuser
- Finding Help
- Moving around the Filesystem
- Manipulating Files and Folders
- System Information Commands
- Searching and Editing Text Files
- Dealing with Users and Groups
- Getting Help on the Command Line
- Searching for Man Files
- Using Wildcards
- Executing Multiple Commands
- Moving to More Advanced Uses of the Command Line
This chapter is from the book
Searching and Editing Text Files
Search and edit text files by using the following commands.
-
grep
: Thegrep
command allows you to search inside a number of files for a particular search pattern and then print matching lines. For example,grep blah
file will search for the text “blah” in the file and then print any matching lines. -
sed
: Thesed
(or Stream EDitor) command allows search and replace of a particular string in a file. For example, if you want to find the string “cat” and replace it with “dog” in a file named pets, typeseds/cat/dog/g pets.
Both grep
and sed
are extremely powerful programs. There are many excellent tutorials available on using them, but here are a couple of good Web sites to get you started:
- https://help.ubuntu.com/community/grep
- http://manpages.ubuntu.com/manpages/precise/man1/9base-sed.1.html
Five other commands are useful for dealing with text.
-
cat:
Thecat
command, short for concatenate, is useful for viewing and adding to text files. The simple commandcat
FILENAME displays the contents of the file. Usingcat
FILENAMEfile
adds the contents of the first file to the second and displays both on the screen, one after the other. You could also usecat file1 >> file2
to append the contents of file1 to the end of file2. -
nano:
Nano is a simple text editor for the command line. To open a file, usenano
filename. Commands listed at the bottom of the screen are accessed via pressing Ctrl followed by the letter. To close and save a file you are working on, use Ctrl-X. -
less
: Theless
command is used for viewing text files as well as standard output. A common usage is to pipe another command throughless
to be able to see all the output, such asls | less
. -
head
: Thehead
command is used for viewing the first 10 lines of text files as well as standard output. A common usage is to pipe another command throughhead
to be able to see varying lines of output, such asls | head
. -
tail
: The tail command is used for viewing the last 10 lines of text files as well as standard output. A common usage is to pipe another command throughtail
to be able to see varying lines of output, such asls | tail
.