3
test1="one  two three   four    five"
echo $test1 | cut -d $'\t' -f2

I have a string which separated by TAB, and I want to get the second word by cut command.

I've found the question How to split a string in bash delimited by tab. But the solution is not used with cut.

Community
  • 1
  • 1
biubiubiu
  • 1,165
  • 3
  • 8
  • 7

4 Answers4

6

This is happening because you need to quote $test1 when you echo:

echo "$test1" | cut -d$'\t' -f2

Otherwise, the format is gone and the tabs converted into spaces:

$ s="hello      bye     ciao"
$ echo "$s"              <--- quoting
hello   bye ciao
$ echo $s                <--- without quotes
hello bye ciao
fedorqui
  • 275,237
  • 103
  • 548
  • 598
2

You don't need cut and can save yourself a fork:

$ test1=$(printf "one\ttwo\three\tfour\tfive")
$ read _ two _ <<< "${test1}"
$ echo "${two}"
two
Adrian Frühwirth
  • 42,970
  • 10
  • 60
  • 71
  • `test1="one two three four five"` from the OP was good enough to define the variable, no need to `printf`. Also, the `{}` in `"${test1}` are not necessary in this case. – fedorqui Oct 15 '14 at 10:08
  • It depends on IFS properly set for tabs so if you changed that previously to e.g. break newlines you should set it again, i.e `IFS=$'\t' read ...` – Andris Jan 09 '20 at 07:12
0

Try to use cut without any -d option:

echo "$test1" | cut -f2

Below is expert from cut man page:

-d, --delimiter=DELIM
    use DELIM instead of TAB for field delimiter 
Fazlin
  • 2,285
  • 17
  • 29
  • actually I've tried this and the result is also the whole test1 string. – biubiubiu Oct 15 '14 at 09:47
  • Check the edited post. I have enclosed `$test1` within double quotes. – Fazlin Oct 15 '14 at 09:53
  • Have you tried `echo $test1` by itself? I see no tabs in the output string... I'd rather use `t="one\tthwo\tthree";echo -e $t|cut -f2` or even `t="one\tthwo\tthree";printf $t|cut -f2`. Ciao – gboffi Oct 15 '14 at 09:56
  • @gboffi the problem is in the quotes itself. Once you do not use them in `echo`, the format is lost. – fedorqui Oct 15 '14 at 09:58
  • @fedorqui - sorry but i did not notice your answer. i just tested my code and update. – Fazlin Oct 15 '14 at 09:58
-3

I run this:

test1="one;two;three;four;five"

echo $test1 | cut -d \; -f2

and get:

two

and your example:

test1="one  two three   four    five"

echo $test1 | cut -d \t -f2

and get:

wo

Hope that helpful.


It's the problem of \t I think.

Love77
  • 1
  • 1
  • 1
    You set the delimiter to be a 't' (escaping it had no effect). Based on that the second field is indeed 'wo '. – Gary_W Oct 15 '14 at 15:00