cut: can we set multiple spaces as the delimiter?

notbad picture notbad · Jan 24, 2014 · Viewed 9k times · Source

I have text like this:

word1 word2   word3  word4

There may be more than one space between a pair of words and I want to get some columns of words from each line . When I use cat file | cut -d ' ' -f1,2,4 it seems that some fields are space which is not what I expected. I know awk can achieve this. The question is can we do this with cut only? i.e., can we set multiple spaces as the delimiter in cut, yet the number varies?

Answer

mklement0 picture mklement0 · Jan 24, 2014

As others have stated, cut can't do it alone (and awk is the best choice, because it's the only tool required). If you still want to use cut, you can combine it with tr, however:

tr -s ' ' <<<"word1 word2   word3  word4" | cut -d ' ' -f1,2,4

tr -s ' ' folds each span of multiple spaces into one space each.