How to split a string in bash delimited by tab

Viewed 105869

I'm trying to split a tab delimitted field in bash.

I am aware of this answer: how to split a string in shell and get the last field

But that does not answer for a tab character.

I want to do get the part of a string before the tab character, so I'm doing this:

x=`head -1 my-file.txt`
echo ${x%\t*}

But the \t is matching on the letter 't' and not on a tab. What is the best way to do this?

Thanks

7 Answers

There is an easy way for a tab separated string : convert it to an array.

Create a string with tabs ($ added before for '\t' interpretation) :

AAA=$'ABC\tDEF\tGHI'

Split the string as an array using parenthesis :

BBB=($AAA) 

Get access to any element :

echo ${BBB[0]}
ABC
echo ${BBB[1]}
DEF
echo ${BBB[2]}
GHI

The answer from https://stackoverflow.com/users/1815797/gniourf-gniourf hints at the use of built in field parsing in bash, but does not really complete the answer. The use of the IFS shell parameter to set the input field separate will complete the picture and give the ability to parse files which are tab-delimited, of a fixed number of fields, in pure bash.

echo -e "a\tb\tc\nd\te\tf" > myfile
while IFS='<literaltab>' read f1 f2 f3;do echo "$f1 = $f2 + $f3"; done < myfile

a = b + c
d = e + f

Where, of course, is replaced by a real tab, not \t. Often, Control-V Tab does this in a terminal.

Related