如何在bash中读取字符串

时间:2013-03-07 01:36:07

标签: bash

我的代码

FOO="dsad; dsadasddas; dadsad; dsdsad asdsdd"
echo "${FOO%%;*}"   
result: dsad

FOO="dsad; dsadasddas; dadsad; dsdsad asdsdd"
echo "${FOO##*;}"
result: dadsad; dsdsad asdsdd

如何打印第一个分号的所有字符?

FOO="dsad; dsadasddas; dadsad; dsdsad asdsdd"
echo "${FOO???}"
result: dsadasddas; dadsad; dsdsad asdsdd

如何在最后一个分号前打印和所有字符?

FOO="dsad; dsadasddas; dadsad; dsdsad asdsdd"
echo "${FOO???}"
result: dsadasddas; dadsad; dsdsad asdsdd

帮助任何人?谢谢;)

1 个答案:

答案 0 :(得分:2)

使用#%代替##%%

foo='one; two; three; four'

# All characters after first semicolon
echo "${foo#*;}"  # two; three; four

# All characters before last semicolon
echo "${foo%;*}"  # one; two; three

${var##glob}${var%%glob}会尽可能地带走(贪婪匹配)。 ${var#glob}${var%glob}将尽可能少地带走(不情愿的匹配)。