Linux 在某些模式之前添加文本时使用忽略大小写的 sed
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16917623/
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
Use sed with ignore case while adding text before some pattern
提问by MaNn
sed -i '/first/i This line to be added'
In this case,how to ignore case while searching for pattern =first
在这种情况下,如何在搜索模式时忽略大小写 =first
采纳答案by fedorqui 'SO stop harming'
You can use the following:
您可以使用以下内容:
sed 's/[Ff][Ii][Rr][Ss][Tt]/last/g' file
Otherwise, you have the /I
and n/i
flags:
否则,你有/I
和 n/i
标志:
sed 's/first/last/Ig' file
From man sed:
来自 man sed:
I
i
The I modifier to regular-expression matching is a GNU extension which makes sed match regexp in a case-insensitive manner.
一世
一世
正则表达式匹配的 I 修饰符是一个 GNU 扩展,它使 sed 以不区分大小写的方式匹配正则表达式。
Test
测试
$ cat file
first
FiRst
FIRST
fir3st
$ sed 's/[Ff][Ii][Rr][Ss][Tt]/last/g' file
last
last
last
fir3st
$ sed 's/first/last/Ig' file
last
last
last
fir3st
回答by Kent
if you want to save some typing, try awk. I don't think sed has that option
如果您想节省一些输入,请尝试 awk。我不认为 sed 有那个选项
awk -v IGNORECASE="1" '/first/{your logic}' file
回答by bendaizer
You can try
你可以试试
sed 's/first/somethingelse/gI'
回答by Endoro
GNU sed
GNU sed
sed '/first/Ii This line to be added' file
回答by Tom Fenech
For versions of awk that don't understand the IGNORECASE
special variable, you can use something like this:
对于不理解IGNORECASE
特殊变量的 awk 版本,您可以使用以下内容:
awk 'toupper(awk -v var="$foo" 'BEGIN { pattern = toupper(foo) } toupper(sed 's/\bfirst\b/This line to be added/Ig' file
) ~ pattern { print "string to insert" } 1' file
) ~ /PATTERN/ { print "string to insert" } 1' file
Convert each line to uppercase before testing whether it matches the pattern and if it does, print the string. 1
is the shortest truecondition, so awk does the default thing: { print }
.
在测试它是否与模式匹配之前将每一行转换为大写,如果匹配,则打印字符串。1
是最短的真实情况,所以awk进行默认的事情:{ print }
。
To use a variable, you could go with this:
要使用变量,你可以这样做:
##代码##This passes the shell variable $foo
and transforms it to uppercase before the file is processed.
这会传递 shell 变量$foo
并将其转换为大写,然后再处理文件。
Slightly shorter with bash would be to use -v pattern="${foo^^}"
and skip the BEGIN
block.
使用 bash 稍微短一点是使用-v pattern="${foo^^}"
和跳过BEGIN
块。
回答by Saurabh
Use the following, \b for word boundary
使用以下命令,\b 表示单词边界
##代码##