Perl 正则表达式:剪切和粘贴 [英] Perl Regex: Cut and Paste

查看:99
本文介绍了Perl 正则表达式:剪切和粘贴的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 perl 来编辑文件,主要是为了在文件中剪切和粘贴内容.但是,看来我错误地构建了正则表达式.我很感激帮助整理它.替换命令 should cut 将 export PATH=$PATH 之后的内容剪切到但 not 包括 # THIS IS LAST>,并在 export PATH=$PATH

I'm attempting to use perl to edit a file, essentially to cut and paste content within the file. However, it appears I've incorrectly constructed the regex. I'd appreciate help in sorting it out. The substitution command should cut cut the content after export PATH=$PATH up to but not including # THIS IS LAST, and paste that content before export PATH=$PATH

Perl 命令:perl -i -pe 's;(export PATH.*\n)(.*)(\# THIS IS LAST!\n);$2$1$3;'bashrc

当前的 bashrc:

Current bashrc:

export TERM=xterm
export PATH=$PATH
export BREW_HOME=/home/dev/.linuxbrew 
export ANACONDA_HOME=/home/dev/.anaconda3

# THIS IS LAST! 

所需的 bashrc:

Desired bashrc:

export TERM=xterm 
export BREW_HOME=/home/dev/.linuxbrew 
export ANACONDA_HOME=/home/dev/.anaconda3
export PATH=$PATH

# THIS IS LAST!

推荐答案

要跨多行匹配,您需要将整个文件放在一个标量中

To match across multiple lines you need to have the whole file in a scalar

perl -0777 -pe's/(export PATH.*?\n)(.*?)(?=\n?# THIS IS LAST)/$2$1/s' input.txt

其中 -0777 启用slurp"模式,并且 (?=...) 是一个 正前瞻.

where -0777 enables "slurp" mode, and (?=...) is a positive lookahead.

\n? 在前瞻中包含不应该被消耗的可选空行,因为该行不应该被移动.那么之前的模式也需要是非贪婪的.这保护了单个前面的空行,任何其他空行都被匹配和交换.

The \n? is in the lookahead to include the optional empty line that shouldn't be consumed, since that line shouldn't be moved. Then the previous pattern need be non-greedy, too. This protects a single preceding empty line, any others are matched and swapped.

这篇关于Perl 正则表达式:剪切和粘贴的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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