Split a String into Parts with `cut` in Bash

Cameron Nokes
InstructorCameron Nokes
Share this video with your friends

Social Share Links

Send Tweet

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.