Even More Looking at Text Files

Even More Looking at Text Files

In the previous sections, we have learned how to use commands like cat, more, less, head, and tail to view the contents of text files. In this section, we will learn about some additional commands that can be used to manipulate and view text files.

grep

grep is a command-line utility for searching text files for specific patterns. The basic syntax for grep is as follows:

grep pattern filename 

For example, let's say we have a file called example.txt that contains the following lines:

apple banana orange grape 

If we wanted to search for the word "orange" in this file, we could use the following command:

grep orange example.txt 


This would return the following output:

orange 


We can also use regular expressions with grep. For example, let's say we wanted to search for any lines in a file that contain a number. We could use the following command:

grep '[0-9]' filename 

This would return all lines that contain a number.

sed

sed is a command-line utility for editing text files. It can be used to find and replace text, insert or delete lines, and perform other operations on text files. The basic syntax for sed is as follows:

sed 's/pattern/replacement/g' filename 

For example, let's say we have a file called example.txt that contains the following lines:

apple banana orange grape 

If we wanted to replace all instances of "orange" with "kiwi" in this file, we could use the following command:

sed 's/orange/kiwi/g' example.txt 

This would replace all instances of "orange" with "kiwi" in the file.

awk

awk is a command-line utility for processing text files. It is particularly useful for working with structured data, such as files that contain columns of data separated by spaces or other delimiters. The basic syntax for awk is as follows:

awk '{pattern + action}' filename 

For example, let's say we have a file called example.txt that contains the following lines:

John 35 25000 Jane 27 30000 Mike 42 50000 

If we wanted to print only the names and ages from this file, we could use the following command:

awk '{print $1, $2}' example.txt 

This would print the following output:

John 35 Jane 27 Mike 42 

Here, $1 and $2 refer to the first and second columns of data in the file.


These are just a few examples of the many commands that can be used to manipulate and view text files in Linux. As you become more familiar with the command line, you will likely discover many more tools and techniques for working with text files.

Complete and Continue