Removing Characters from Output with cut

The cut command lets you remove text from the output stream or from a file.

Give it a try:

 $ ​​echo​​ ​​'hello world'​​ ​​|​​ ​​cut​​ ​​-c​​ ​​2-4
 ell

Here’s how it works. The -c flag tells cut to cut at characters, rather than bytes. The value is 2-4, which tells cut to cut out everything other than characters 2 through 4.

You can also specify that you want everything from the beginning of the string until the specified position. For example, to grab just the first five characters, use -c -5:

 $ ​​echo​​ ​​'hello world'​​ ​​|​​ ​​cut​​ ​​-c​​ ​​-5
 hello

Using -c 7-, you can grab everything from the seventh character until the end of the line:

 $ ​​echo​​ ​​'hello world'​​ ​​|​​ ​​cut​​ ​​-c​​ ​​7-
 world

Let’s try something more practical by using cut to manipulate the output of the history command. As you recall, when you execute history, you’ll see two columns of output—the history number and the command:

 $ ​​history
  5 ls
  6 cd Documents/
  7 cd
  8 history
  ...

You can use the cut command to remove the numerical column:

 $ ​​history​​ ​​|​​ ​​cut​​ ​​-c​​ ​​8-
 ls
 cd Documents/
 cd
 history
 ...

Notice that cut operates on each line of the output. Combine this with redirection to save this to a text file:

 $ ​​history​​ ​​|​​ ​​cut​​ ​​-c​​ ​​8-​​ ​​>​​ ​​commands.txt

The cut command can also operate on fields. It uses tabs by default. Try it out. Use the echo command with the -e switch to print out a string with some tabs, using for the tab character. Then, use cut to pull out the individual fields:

 $ ​​echo​​ ​​-e​​ ​​"hello world"​​ ​​|​​ ​​cut​​ ​​-f​​ ​​1
 hello
 $ ​​echo​​ ​​-e​​ ​​"hello world"​​ ​​|​​ ​​cut​​ ​​-f​​ ​​2
 world

You can specify a different delimiter, like a comma, using the -d switch. Create a quick CSV file:

 $ ​​cat​​ ​​<<​​ ​​'EOF'​​ ​​>​​ ​​contacts.txt
 >​​ ​​Homer,Simpson,939-555-4795,742​​ ​​Evergreen​​ ​​Terrace
 >​​ ​​EOF

Then, use cut to pull out the third field in the file:

 $ ​​cut​​ ​​-d​​ ​​','​​ ​​-f​​ ​​3​​ ​​contacts.txt
 939-555-4795

The cut command is a good fit for simple use cases where you’re working with uniform content, but it’s not always the best tool for the job. For example, it’s not the best tool for extracting fields from the ls -l command, as that output is separated by spaces. Tools like awk are a better fit for that, and you’ll get to that later in this chapter.

But first, let’s look at how to sort results.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.20.224.107