如何使用bash查找字符串中包含的单词的第一个字母。查找字符串中每个单词的第一个字母
例如
代码:
str="my-custom-string'
我希望找到M,C,S。我知道如何找到第一个字母,但这稍微复杂一些。 非常感谢,
如何使用bash查找字符串中包含的单词的第一个字母。查找字符串中每个单词的第一个字母
例如
代码:
str="my-custom-string'
我希望找到M,C,S。我知道如何找到第一个字母,但这稍微复杂一些。 非常感谢,
$ echo 'my-custom-string' | egrep -o '\b\w'
m
c
s
使用参数替换的纯Bash。删除减,选择每个单词的第一个字符:
str="my-custom-string"
for word in ${str//-/ }; do
echo "${word:0:1}"
done
结果
m
c
s
这里有一个sed
版本:
echo 'my-custom-string' | sed 's/\(^\|-\)\(.\)[^-]*/\2\n/g'
这可能会为你工作(GNU SED)
echo 'my-custom-string' | sed 's/\B.//g;y/-/,/'
m,c,s
或:
echo 'my-custom-string' | sed 's/\B.//g;y/-/\n/'
m
c
s
“我知道如何寻找的第一个字母”,并没有告诉我们,向我们展示[你已经试过(http://whathaveyoutried.com/ )和你卡住的地方。 – Johnsyweb 2012-07-08 10:35:36
str ='my-custom-string'; echo $ {str:0:1} – 2012-07-08 11:13:10