且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用sed获取单词的第一个字母

更新时间:2023-02-05 14:59:45

可能有更简洁的方法,但是以下方法似乎可行:

There's probably a neater way of doing this, but the following seems to work:

$ echo 'Ken Van de Wilde' | sed 's/\(\w\)\w*\( \|$\)/\1/g'
KVdW
$ echo 'Ruben Van Den Bosshe' | sed 's/\(\w\)\w*\( \|$\)/\1/g'
RVDB

要稍微分解一下该正则表达式,它依次匹配以下内容:

To break down that regular expression a bit, it matches the following in turn:

  • 在第一组中捕获的单词字母: \(\ w \)
  • 零个或多个单词字母: \ w *
  • 最后,是空格或行尾: \(\ | $ \)

该序列将替换为第一组中捕获的所有序列: \ 1

That sequence is replaced with whatever was captured in the first group: \1