Use sed with ignore case while adding text before

2020-02-01 06:52发布

sed -i '/first/i This line to be added' 

In this case,how to ignore case while searching for pattern =first

标签: linux unix sed
6条回答
Lonely孤独者°
2楼-- · 2020-02-01 07:29

if you want to save some typing, try awk. I don't think sed has that option

 awk -v IGNORECASE="1" '/first/{your logic}' file
查看更多
混吃等死
3楼-- · 2020-02-01 07:35

You can use the following:

sed 's/[Ff][Ii][Rr][Ss][Tt]/last/g' file

Otherwise, you have the /I and n/i flags:

sed 's/first/last/Ig' file

From 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.

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
查看更多
我想做一个坏孩纸
4楼-- · 2020-02-01 07:36

GNU sed

sed '/first/Ii This line to be added' file
查看更多
虎瘦雄心在
5楼-- · 2020-02-01 07:42

Use the following, \b for word boundary

sed 's/\bfirst\b/This line to be added/Ig' file
查看更多
干净又极端
6楼-- · 2020-02-01 07:45

For versions of awk that don't understand the IGNORECASE special variable, you can use something like this:

awk 'toupper($0) ~ /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 true condition, so awk does the default thing: { print }.

To use a variable, you could go with this:

awk -v var="$foo" 'BEGIN { pattern = toupper(foo) } toupper($0) ~ pattern { print "string to insert" } 1' file

This passes the shell variable $foo and transforms it to uppercase before the file is processed.

Slightly shorter with bash would be to use -v pattern="${foo^^}" and skip the BEGIN block.

查看更多
神经病院院长
7楼-- · 2020-02-01 07:49

You can try

sed 's/first/somethingelse/gI'
查看更多
登录 后发表回答