How can I cut(1) camelcase words?

时间秒杀一切 提交于 2019-12-04 03:31:21

sed 's/\([A-Z]\)/ \1/g'

Captures each capital letter and substitutes a leading space with the capture for the whole stream.

$ echo "aCertainCamelCasedWord" | sed 's/\([A-Z]\)/ \1/g'
a Certain Camel Cased Word
gerardw

This solution works if you need to not split up words that are all caps. For example, using the top answer you'll get:

$ echo 'FAQPage' | sed 's/\([A-Z]\)/ \1/g' 
F A Q Page

But instead with my solution, you'll get:

$ echo 'FAQPage' | sed 's/\([A-Z][^A-Z]\)/ \1/g'
FAQ Page

Note: This does not work correctly when there is a second instance of multiple uppercase words, for example:

$ echo 'FAQPageOneReplacedByFAQPageTwo' | sed 's|\([A-Z][^A-Z]\)| \1|g'
FAQ Page One Replaced ByFAQ Page Two
J G Miller

This answer does not work correctly when there is a second instance of multiple uppercase

echo 'FAQPageOneReplacedByFAQPageTwo' | sed 's|\([A-Z][^A-Z]\)| \1|g'
FAQ Page One Replaced ByFAQ Page Two

So and additional expression is required for that

 echo 'FAQPageOneReplacedByFAQPageTwo' | sed -e 's|\([A-Z][^A-Z]\)| \1|g' -e 's|\([a-z]\)\([A-Z]\)|\1 \2|g'
 FAQ Page One Replaced By FAQ Page Two

Pure Bash:

name="aCertainCamelCasedWord"

declare -a word                                 # the word array

counter1=0                                      # count characters
counter2=0                                      # count words

while [ $counter1 -lt ${#name} ] ; do
  nextchar=${name:${counter1}:1}
  if [[ $nextchar =~ [[:upper:]] ]] ; then
    ((counter2++))
    word[${counter2}]=$nextchar
  else
    word[${counter2}]=${word[${counter2}]}$nextchar
  fi
  ((counter1++))
done

echo -e "'${word[@]}'"
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!