test1="one two three four five"
echo $test1 | cut -d $'\t' -f2
我有一个由
TAB
分隔的字符串,我想用cut
命令获取第二个单词。
我找到了这个问题:如何在bash中以制表符为分隔符拆分字符串。但是该解决方案没有使用cut
命令。test1="one two three four five"
echo $test1 | cut -d $'\t' -f2
TAB
分隔的字符串,我想用cut
命令获取第二个单词。
我找到了这个问题:如何在bash中以制表符为分隔符拆分字符串。但是该解决方案没有使用cut
命令。echo
时需要引用$test1
变量:echo "$test1" | cut -d$'\t' -f2
$ s="hello bye ciao"
$ echo "$s" <--- quoting
hello bye ciao
$ echo $s <--- without quotes
hello bye ciao
cut
命令,可以避免创建新的进程:$ test1=$(printf "one\ttwo\three\tfour\tfive")
$ read _ two _ <<< "${test1}"
$ echo "${two}"
two
-d
选项的情况下使用cut
:echo "$test1" | cut -f2
cut
命令手册的专家摘录:-d, --delimiter=DELIM
use DELIM instead of TAB for field delimiter
$test1
。 - Fazlinecho $test1
吗?我在输出字符串中没有看到制表符... 我宁愿使用 t="one\tthwo\tthree";echo -e $t|cut -f2
或者 t="one\tthwo\tthree";printf $t|cut -f2
。再见。 - gboffiecho
中不使用它们,格式就会丢失。 - fedorquitest1="one;two;three;four;five"
echo $test1 | cut -d \; -f2
并获得:
two
以及你的例子:
test1="one two three four five"
echo $test1 | cut -d \t -f2
并获取:
wo
希望对你有所帮助。
我认为这是制表符的问题。
test1="one two three four five"
已经足够好地定义了变量,不需要使用printf
。此外,在这种情况下,"${test1}
中的{}
是不必要的。 - fedorquiIFS = $'\t' read ...
- Andris