How to split a string in bash delimited by tab
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 input1st-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-field2:1st-field 2nd-field3:1st-field 2nd-field4:1st-field 2nd-field5:1st-field 2nd-field6:1st-field 2nd-field7:1st-field 2nd-field8:1st-field 2nd-field9:1st-field 2nd-field10:1st-field 2nd-field
Solution using awk:
$ awk 'END {print $1}' input10:1st-field
Pure bash-solution:
#!/bin/bashwhile read a b;do last=$a; done < inputecho $last
outputs:
$ ./tab.sh 10:1st-field
Lastly, a solution using sed
$ sed '$s/\(^[^\t]*\).*$/\1/' input10: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
Use $'ANSI-C'
strings in the parameter expansion:
$ x=$'abc\tdef\tghi'$ echo "$s"abc def ghi$ echo ">>${x%%$'\t'*}<<">>abc<<
read field1 field2 <<< ${tabDelimitedField}
or
read field1 field2 <<< $(command_producing_tab_delimited_output)