user3239835
user3239835

Reputation: 75

extract a particular sequence from a file

I have a file which has space separator which are unequally spaced like,

john  0101 C1     Comp  
mayo 0120 D2     Comp
peter  0110 E1     IT

etc. I want to extract all values from file in a separate fields. I tried using cut like,

cut -f1,2,3 -d " " line1

but only first name is getting extracted correctly not remaining. I think problem is with unequal spaces.please suggest me any solution on this.
Apologies if its a very easy question.

Upvotes: 0

Views: 48

Answers (2)

Nachiket Kate
Nachiket Kate

Reputation: 8571

There is tr command present which can rescue you from this situation,

translate multiple occurences of single character into 1

echo $line | tr -s " " | cut -f1,2,3 -d " "

will do for you. even Awk can also help

awk '{print $1, $2, $3}' (remaining fields also)

Upvotes: 2

anubhava
anubhava

Reputation: 785731

It is because cut doesn't work well with multiple occurrences of delimiters.

You can use awk instead:

awk '{print $1, $2, $3}' file

Alternatively you can use tr -s ' ' to squeeze multiple spaces:

tr -s ' ' < file | cut -f1,2,3 -d " "

Upvotes: 8

Related Questions