Search code examples
shellcut

how to split string by tab in bash


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.


Solution

  • 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