How to use when cut doesn’t cut it

command linecut

I have a file cities like this:

[1598] San Diego, US (inactive)
[4517] St Louis, US (inactive)
[6346] Orlando, US (inactive)

I want to cut out the city names, so that I have:

San Diego
St Louis
Orlando

This is the best I could come up with:

cut -d ',' -f1 cities | cut -d ']' -f2

But that still leaves me with a space before the names. Is there a cut like command that I can use that accept delimiters of several characters so I can cut on ]?

Best Answer

Awk (also check Awk Info) is beautiful with that sort of question. Try:

awk -F'[],] *' '{print $2}' cities

This defines a field separator -F as [],] * - which means one occurence of either a closing square bracket or a comma, followed by zero or any number of spaces. Of course you can change that to suit any requirement. Read up on regular expressions.

Once the line is split, you can do what you want with the split result. Here, I decided to print out the second field only with print $2. Note that it is important to use single quotes around the awk instructions otherwise $2 gets substituted by the shell.

Related Question