Perl 命令行多行替换 [英] Perl command line multi-line replace
问题描述
我正在尝试使用命令行 perl 替换多行文件中的文本.我正在使用 Ubuntu Natty.
I'm trying to replace text in a multi-line file using command-line perl. I'm using Ubuntu Natty.
以下是我的文本文件(名为 test.txt)的内容:
Below is the content of my text file (called test.txt):
[mysqld]
#
# * Basic Settings
#
#
# * IMPORTANT
# If you make changes to these settings and your system uses apparmor, you may
# also need to also adjust /etc/apparmor.d/usr.sbin.mysqld.
#
user = mysql
socket = /var/run/mysqld/mysqld.sock
port = 3306
basedir = /usr
datadir = /var/lib/mysql
tmpdir = /tmp
skip-external-locking
下面是我的 perl 命令:
Below is my perl command:
perl -i -pe "s/([mysqld][^^]+)/1
sometext/g" test.txt
然而,不是替换文件中的所有文本,下面是我最终得到的:
However, instead of replacing all the text in the file, below is what I end up with:
[mysqld]
sometext#
# * Basic Settings
#
#
# * IMPORTANT
# If you make changes to these settings and your system uses apparmor, you may
# also need to also adjust /etc/apparmor.d/usr.sbin.mysqld.
#
user = mysql
socket = /var/run/mysqld/mysqld.sock
port = 3306
basedir = /usr
datadir = /var/lib/mysql
tmpdir = /tmp
skip-external-locking
#
我在 RegexBuddy 中为 Perl 尝试了 Regex,它匹配文本文件中的所有内容,但由于某种原因,它无法在命令行上使用 perl.
I tried the Regex in RegexBuddy for Perl and it matches everything in the text file, but for some reason it's not working using perl on the command line.
希望得到一些帮助.
提前致谢.
推荐答案
您正在逐行读取文件,因此只有第一行与您的正则表达式匹配.你想要做的——如果你真的想删除大部分内容——是使用 -0
选项来吞食文件,例如<代码>-0777代码>.这是行尾处理,777
只是一个约定俗成的数字,作为一个足够大的八进制数,以致导致文件噼啪声.
You are reading the file line-by-line, so only the first line matches your regex. What you'll want to do -- if you truly wish to delete most of the content -- is to slurp the file by using the -0
option, e.g. -0777
. This is line ending processing, and 777
is just a number used by convention as an octal number large enough so as to cause file slurping.
perl -0777 -i -pe 's/([mysqld][^^]+)/$1
sometext/g' test.txt
另外,我替换了你的引号.如果你在 *nix 中,看起来你是,单引号更可取.例如,$1
不会被 shell 插入.
Also, I replaced your quotes. If you are in *nix, which it seems you are, single quotes are preferable. Case in point, $1
would not be interpolated by the shell.
这篇关于Perl 命令行多行替换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!