Split a String into Parts with `cut` in Bash

Cameron Nokes
InstructorCameron Nokes
Share this video with your friends

Social Share Links

Send Tweet
Published 4 years ago
Updated 3 years ago

cut makes it quick and easy to break a string into parts based on a delimiter or get a substring. In practice, it’s somewhat similar to JavaScript’s String.split method. In this video, we’ll look at using cut to work with semver strings and truncate a long string.

Cameron Nokes: [0:00] Let's say I have a SemVer number like this and I want to know just the minor version for this middle number right here, the 10, OK? Then I'm going to do -d. The d flags, obviously, stands for delimiter.

[0:12] My delimiter is going to be this period. Note that I'm going to wrap that in single quotes so that dash isn't interpreted as some other symbol. Conceptually what happens here it's going to cut this into three parts, 1, 10, and 3.

[0:26] Then from there we need to select which part or field we want. The f flag here stands for field. I want the second field. It's going to get me 10. That's working. We can just try it with the other ones. There's 3 and 1. Cool, that works.

[0:44] If we wanted multiple fields, we can do that like this. If I want both the one and the two, you just use that comma to separate the fields that you want.

[0:54] That's how cut works with a character delimiter. Let's see how cutting on character position works.

[0:58] I have my string there. Now we're going to do cut. Then we're going to pass the c flag, which stands for character. If I just wanted the first character, I could do that. There's a second character. I can also pass a range here. If I wanted characters 1 through 10, I can do that. That could be a handy way to truncate long strings.

egghead
egghead
~ an hour ago

Member comments are a way for members to communicate, interact, and ask questions about a lesson.

The instructor or someone from the community might respond to your question Here are a few basic guidelines to commenting on egghead.io

Be on-Topic

Comments are for discussing a lesson. If you're having a general issue with the website functionality, please contact us at support@egghead.io.

Avoid meta-discussion

  • This was great!
  • This was horrible!
  • I didn't like this because it didn't match my skill level.
  • +1 It will likely be deleted as spam.

Code Problems?

Should be accompanied by code! Codesandbox or Stackblitz provide a way to share code and discuss it in context

Details and Context

Vague question? Vague answer. Any details and context you can provide will lure more interesting answers!

Markdown supported.
Become a member to join the discussionEnroll Today