Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cut: can we set multiple spaces as the delimiter?

Tags:

bash

shell

cut

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?

like image 986
notbad Avatar asked Jan 24 '14 01:01

notbad


2 Answers

use awk, bro: awk '{print $1, $2, $4;}' file

Thank you @fedorqui for the sugesstion

like image 63
user3159253 Avatar answered Oct 08 '22 08:10

user3159253


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.

like image 27
mklement0 Avatar answered Oct 08 '22 09:10

mklement0