如何在bash中按标签分割字符串

时间:2014-10-15 09:40:47

标签: shell cut

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

我有一个以TAB分隔的字符串,我希望通过cut命令得到第二个字。

我发现了问题How to split a string in bash delimited by tab。但该解决方案不与cut一起使用。

4 个答案:

答案 0 :(得分:4)

这种情况正在发生,因为您需要$test1时引用echo

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

否则,格式消失,标签转换为空格:

$ s="hello      bye     ciao"
$ echo "$s"              <--- quoting
hello   bye ciao
$ echo $s                <--- without quotes
hello bye ciao

答案 1 :(得分:2)

你不需要cut并且可以为自己省钱:

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

答案 2 :(得分:0)

尝试使用cut而不使用任何-d选项:

echo "$test1" | cut -f2

以下是来自cut手册页的专家:

-d, --delimiter=DELIM
    use DELIM instead of TAB for field delimiter 

答案 3 :(得分:-3)

我跑了这个:

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

echo $test1 | cut -d \; -f2

并获得:

two

和你的例子:

test1="one  two three   four    five"

echo $test1 | cut -d \t -f2

并获得:

wo

希望有帮助。


这是我认为的问题。