[英]sed regex matching not working
I want to update the year in licence header of the source code in many files. 我想在许多文件中更新源代码的许可证标头中的年份。 I am writing bash sript for that.
我正在为此写bash sript。 However the sed command is not working.
但是sed命令不起作用。 In particular, the regex fails to match and replace the desired word.
特别是,正则表达式无法匹配和替换所需的单词。
Example: mycode.h 示例:mycode.h
<Some Multi Line text>
Copyright 2002-2014 Utkrist Adhikari
<Some Multi Line text>
Lets say I want to replace 2014 by 2015 ( END_DATE=2015 ). 假设我想在2015年之前替换2014( END_DATE = 2015 )。 I am trying to achieve it with following command:
我正在尝试通过以下命令实现它:
sed -i -r "s/\(Copyright.*\)-[ ]*[0-9]+[ ]*\( Utkrist Adhikari\)/\1$END_DATE\2/" mycode.h
OR 要么
sed '/Copyright/,/Peter Baumann/ {s/-[ ]*[0-9]+[ ]*/$END_DATE/}' $file
Basically, I am trying to match 基本上,我正在尝试匹配
I would then like to replace the middle part with content of the variable END_DATE 然后,我想用变量END_DATE的内容替换中间部分
You could try the below GNU sed command, 您可以尝试以下GNU sed命令,
$ END_DATE=2015; sed -r "s/^(Copyright\s*[0-9]{4}-)[0-9]{4}(\s*Utkrist\s*Adhikari)/\1$END_DATE\2/g" file
<Some Multi Line text>
Copyright 2002-2015 Utkrist Adhikari
<Some Multi Line text>
sed -r "s/^(Copyright 2002-)[0-9]{4}( Utkrist Adhikari)$/\1$END_DATE\2/" mycode.h
Here is a simple way to do it with awk
这是使用
awk
的简单方法
awk '/Copyright/ {sub(/-[0-9]*/,"-2015")}1' file
<Some Multi Line text>
Copyright 2002-2015 Utkrist Adhikari
<Some Multi Line text>
When data comes from a variable: 当数据来自变量时:
END_DATE=2015
awk -v d="$END_DATE" '/Copyright/ {sub(/-[0-9]*/,"-"d)}1' file
<Some Multi Line text>
Copyright 2002-2015 Utkrist Adhikari
<Some Multi Line text>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.