如何使用 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