我是Perl的新手,正在尝试使用通配符替换文本文件中的一行。示例文件:
This is a text file.
我的工作(非通配符)示例:
file=/home/test.user/test.txt
perl -pi -e 's/This is a text file./'"This is a modified text file."'/g' $file
现在尝试使用通配符进行编辑:
perl -pi -e 's/This*/'"This is a modified text file."'/g' $file
这是不正确的,并输出:
This is a modified text file. is a text file.
如何对/This*/
使用通配符搜索?
答案 0 :(得分:1)
Perl的s///
使用正则表达式模式来匹配目标,而不是shell glob字符串。
尝试使用*
代替.*
:
perl -pi -e 's/This.*/'"This is a modified text file."'/g' $file
.*
匹配零或出现任何字符,但换行符LF
或"\n"
除外。
请小心,因为它将与字符串中的子字符串“ 任意位置”匹配。所以这个字符串:
If This is a text file
将成为以下字符串:
If This is a modified text file
因此,如果要匹配行首,请使用 anchor ^
,它坚持要求模式的其余部分必须在字符串的开头匹配
perl -pi -e 's/^This.*/'"This is a modified text file."'/g' $file