How to transfer characters between uppercase and lowercase with sed

泄露秘密 提交于 2019-12-25 02:46:53

问题


For example, my src.tex is

SectionType *p = NULL;

and I want it change to

section_type *p = NULL;

what I want to do is just change the SectionType, but remains the NULL unchanged, I used y/[A-Z]/[a-z], but this will change all the line.

My sed do not support \L,\l,\U and \u functions, it version is 3.* and distributed under FSF, not GNU, may be GNU's works well with this functions, but at the time I could not adopt the GNU's because I'm working in msys and there is no GNU package.

Is there any solution to get it?


回答1:


From here

Convert CamelCase or camelCase to camel_case:

sed -e 's/\([A-Z][a-z]\)/_\l\1/g' -e 's/^_\([a-z]\)/\1/g' file.txt

Input:

SectionType *p = NULL;
sectionType *p = NULL;
ABCSectionType *p = NULL;

Output:

section_type *p = NULL;
section_type *p = NULL;
ABC_section_type *p = NULL;



回答2:


This should work without having to install another version of sed. It changes the case only on the first word of the line.

upper=$(printf "%s" {A..Z})
lower=$(printf "%s" {a..z})
sed "s/ /\n/;h;s/[^\n]*\n//;x;s/\n.*//;y/$upper/$lower/;G;s/\n//" inputfile

My version of sed won't do y/[A-Z]/[a-z]/, it needs each character explicitly included which is why I used the variables. The way I created them depends on a feature that only some shells, such as Bash and ksh, have. You can do a simple assignment or use the range if your sed supports it.

If your version of sed is really picky, it may want -e instead of semicolons. This version should work in that case:

sed -e "s/ /\n/" -e "h" -e "s/[^\n]*\n//" -e "x" -e "s/\n.*//" -e "y/$upper/$lower/" -e "G" -e "s/\n//" inputfile


来源:https://stackoverflow.com/questions/4130205/how-to-transfer-characters-between-uppercase-and-lowercase-with-sed

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