Pep
Pep

Reputation: 2027

How can I split parts of a bash variable separated with tabs?

I want to extract the fields in a bash script variable named $DequeuedItem. Fields are tab-delimited.

I tried with the following sentence:

DequeuedItemF1=$(echo $DequeuedItem | cut -f1)

But DequeuedItemF1 gets the whole $DequeuedItem, and it seems that tabs become regular spaces. Is the echo command doing a conversion of the tabs before the stream reaches the cut command?

Upvotes: 0

Views: 999

Answers (1)

Adam Liss
Adam Liss

Reputation: 48310

When you echo an unquoted variable, tabs are changed to spaces. Double-quotes will preserve the tabs:

DequeuedItemF1=$(echo "$DequeuedItem" | cut -f1)

If the DequeuedItem contains no internal spaces, you could also use

DequeuedItemF1=$(echo $DequeuedItem | cut -d\  -f1)

but the first option is both clearer and more robust. (Note that there are two spaces after the backslash. The backslash escapes the first space, which becomes the delimiter for cut, and the second space separates the -d option from the -f option. Confusing, and all the more reason to use the other choice!)

Upvotes: 1

Related Questions