Use sed with ignore case while adding text before some pattern

后端 未结 6 1254
名媛妹妹
名媛妹妹 2020-12-06 17:26
sed -i \'/first/i This line to be added\' 

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

6条回答
  •  无人及你
    2020-12-06 17:46

    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.

提交回复
热议问题