bash 将文件从驼峰式大小写转换为下划线的 awk/sed 脚本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28795479/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 12:27:12  来源:igfitidea点击:

Awk/sed script to convert a file from camelCase to underscores

bashawksedcamelcasing

提问by Corentin Peuvrel

I want to convert several files in a project from camelCaseto underscore_case.

我想几个文件转换,从一个项目camelCaseunderscore_case

I would like to have a onliner that only needs the filename to work.

我想要一个只需要文件名就可以工作的在线工具。

回答by Avinash Raj

You could use sed also.

您也可以使用 sed。

$ echo 'fooBar' | sed -r 's/([a-z0-9])([A-Z])/_\L/g'
foo_bar
$ echo 'fooBar' | sed 's/\([a-z0-9]\)\([A-Z]\)/_\L/g'
foo_bar

回答by pachopepe

The proposed sedanswer has some issues:

建议的sed答案有一些问题:

$ echo 'FooBarFB' | sed -r 's/([a-z0-9])([A-Z])/_\L/g'
Foo_bar_fB

I sugesst the following

我建议以下

$ echo 'FooBarFB' | sed -r 's/([A-Z])/_\L/g' | sed 's/^_//'
foo_bar_f_b

回答by Corentin Peuvrel

After a few unsuccessful tries, I got this (I wrote it on several lines for readability, but we can remove the newlines to have a onliner) :

经过几次不成功的尝试后,我得到了这个(为了可读性,我把它写在几行上,但我们可以删除换行符以获得在线):

awk -i inplace '{
  while ( match(
awk -i inplace '{
  while ( match(
awk '{...}' FILE > FILE.tmp && mv FILE.tmp FILE
, /(.*)([a-z0-9])_([a-z])(.*)/, cap))
$ cat tst.awk
{
    head = ""
    tail = ##代码##
    while ( match(tail,/[[:upper:]]/) ) {
        tgt = substr(tail,RSTART,1)
        if ( substr(tail,RSTART-1,1) ~ /[[:lower:]]/ ) {
            tgt = "_" tolower(tgt)
        }
        head = head substr(tail,1,RSTART-1) tgt
        tail = substr(tail,RSTART+1)
    }
    print head tail
}

$ cat file
nowIs theWinterOfOur disContent
From ThePlay About RichardIII

$ awk -f tst.awk file
now_is the_winter_of_our dis_content
From The_play About Richard_iII
= cap[1] cap[2] toupper(cap[3]) cap[4]; print }' FILE
, /(.*)([a-z0-9])([A-Z])(.*)/, cap)) ##代码## = cap[1] cap[2] "_" tolower(cap[3]) cap[4]; print }' FILE

For the sake of completeness, we can adapt it to do the contrary (underscore to CamelCase) :

为了完整起见,我们可以将它改写成相反的(CamelCase 下划线):

##代码##

If you're wondering, the -i inplaceis a flag only available with awk >=4.1.0, and it modify the file inplace (as with sed -i). If you're awk version is older, you have to do something like :

如果您想知道,这-i inplace是一个仅适用于 awk >=4.1.0 的标志,并且它就地修改文件(与 一样sed -i)。如果您的 awk 版本较旧,则必须执行以下操作:

##代码##

Hope it could help someone !

希望它可以帮助某人!

回答by Ed Morton

This might be what you want:

这可能是你想要的:

##代码##

but without your sample input and expected output it's just a guess.

但没有您的样本输入和预期输出,这只是一个猜测。