biubiubiu
biubiubiu

Reputation: 1375

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.

Upvotes: 3

Views: 11298

Answers (4)

Love77
Love77

Reputation: 1

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.

Upvotes: -3

Adrian Frühwirth
Adrian Frühwirth

Reputation: 45626

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

$ test1=$(printf "one\ttwo\three\tfour\tfive")
$ read _ two _ <<< "${test1}"
$ echo "${two}"
two

Upvotes: 2

Fazlin
Fazlin

Reputation: 2337

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 

Upvotes: 0

fedorqui
fedorqui

Reputation: 290025

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

Upvotes: 6

Related Questions