Perl命令行多行替换 [英] Perl command line multi-line replace

查看:539
本文介绍了Perl命令行多行替换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用命令行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\nsometext/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\nsometext/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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆