coanor
coanor

Reputation: 3962

How to transfer characters between uppercase and lowercase with sed

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?

Upvotes: 0

Views: 1002

Answers (2)

Dennis Williamson
Dennis Williamson

Reputation: 360683

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

Upvotes: 1

Brian Clements
Brian Clements

Reputation: 3915

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;

Upvotes: 1

Related Questions