bash sed 将两个字符串之间的小写字符串替换为大写

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22718518/
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 10:03:03  来源:igfitidea点击:

Sed to replace lower case string between two strings to upper case

regexbashsed

提问by Sathish

i have a text file as below. I want to change the lower string between fooand varto upper case.

我有一个文本文件,如下所示。我想改变的低串foovar为大写。

foo nsqlnqnsslkqn var
lnlnl.
foo DkqdQ HNOQii var

my expected output is

我的预期输出是

foo NSQLNQNSSLKQN var
lnllnl.
foo DKQDQ HNOQII var

i have used a one liner using sed sed 's/\(\foo\).*\(\var\)/\U\1\2/' testfile.txtbut i get the following output

我已经使用 sed 使用了单衬,sed 's/\(\foo\).*\(\var\)/\U\1\2/' testfile.txt但我得到以下输出

FOOVAR
lnlnl.
FOOVAR

回答by fedorqui 'SO stop harming'

You can use \Uto make something become upper case:

您可以使用\U使某些内容变为大写:

$ sed 's/.*/\U&/' <<< "hello"
HELLO

And \Eto stop the conversion:

\E停止转换:

$ sed -r 's/(..)(..)(.)/\U\E\U/' <<< "hello"
HEllO


In your case, just catch the blocks and place those \Uand \Eaccordingly:

在你的情况,正好赶上块,并把这些\U\E相应的:

$ sed -r 's/(foo )(.*)( var)/\U\E/' file
foo NSQLNQNSSLKQN var
lnlnl.
foo DKQDQ HNOQII var
  • (foo )(.*)( var)catches three blocks: foo, the next text and var.
  • \1\U\2\E\3prints them back, upcasing (is it a verb?) the second one (\U) and using the current case (\E) for the 3rd.
  • (foo )(.*)( var)捕获三个块:foo、下一个文本和var
  • \1\U\2\E\3将它们打印回来,大写(它是动词吗?)第二个 ( \U) 并使用当前案例 ( \E) 作为第三个。

Without -r, to make it more similar to your current approach:

没有-r, 使其更类似于您当前的方法:

sed 's/\(foo \)\(.*\)\( var\)/\U\E/' file

So you can see that you were not catching the .*block, so you were printing back just fooand var.

所以你可以看到你没有捕捉到.*块,所以你只是打印了foovar



From the manual of sed:

sed 手册

\LTurn the replacement to lowercase until a \U or \E is found,

\lTurn the next character to lowercase,

\UTurn the replacement to uppercase until a \L or \E is found,

\uTurn the next character to uppercase,

\EStop case conversion started by \L or \U.

\L将替换转为小写,直到找到 \U 或 \E,

\l将下一个字符转为小写,

\U将替换转为大写,直到找到 \L 或 \E,

\u将下一个字符转为大写,

\E停止由 \L 或 \U 开始的大小写转换。