Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split a string in bash delimited by tab

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

like image 393
chaimp Avatar asked Jul 11 '11 18:07

chaimp


People also ask

How do you split a line in a word in shell script?

The -a option of read will allow you to split a line read in by the characters contained in $IFS . #!/bin/bash filename=$1 while read LINE do echo $LINE | read -a done < $filename should it work?

How do I split a string in a tab?

Use str. rstrip() and Regex Method to Divide Given String by Tab in Python.

How do I split a string on a delimiter in bash?

In bash, a string can also be divided without using $IFS variable. The 'readarray' command with -d option is used to split the string data. The -d option is applied to define the separator character in the command like $IFS. Moreover, the bash loop is used to print the string in split form.

How split a string in bash Linux?

According to the script, a text value with the colon(:) has to take as input for splitting. Here, 'readarray' command with -d option is used to split the string data. '-d' option is used to define the separator character in the command like $IFS. Next, 'for' loop is used to print the array elements.


2 Answers

If your file look something like this (with tab as separator):

1st-field   2nd-field 

you can use cut to extract the first field (operates on tab by default):

$ cut -f1 input 1st-field 

If you're using awk, there is no need to use tail to get the last line, changing the input to:

1:1st-field     2nd-field 2:1st-field     2nd-field 3:1st-field     2nd-field 4:1st-field     2nd-field 5:1st-field     2nd-field 6:1st-field     2nd-field 7:1st-field     2nd-field 8:1st-field     2nd-field 9:1st-field     2nd-field 10:1st-field    2nd-field 

Solution using awk:

$ awk 'END {print $1}' input 10:1st-field 

Pure bash-solution:

#!/bin/bash  while read a b;do last=$a; done < input echo $last 

outputs:

$ ./tab.sh  10:1st-field 

Lastly, a solution using sed

$ sed '$s/\(^[^\t]*\).*$/\1/' input 10:1st-field 

here, $ is the range operator; i.e. operate on the last line only.

For your original question, use a literal tab, i.e.

x="1st-field    2nd-field" echo ${x%   *} 

outputs:

1st-field 
like image 124
Fredrik Pihl Avatar answered Sep 22 '22 20:09

Fredrik Pihl


Use $'ANSI-C' strings in the parameter expansion:

$ x=$'abc\tdef\tghi' $ echo "$s" abc     def     ghi $ echo ">>${x%%$'\t'*}<<" >>abc<< 
like image 45
glenn jackman Avatar answered Sep 22 '22 20:09

glenn jackman