如何修改多行模式?

时间:2016-03-31 10:24:46

标签: regex perl awk sed csh

我有一个文件,如:

....
sth
Q-[N1] your name?
A1-My first name is Joe
A2-My Last name is  Jim
sth
sth
....
....
sth
Q-[N2] your name?
A1-My first name is Jack
A2-My Last name is  JUNE
sth
sth
....

我想在以Q-开头的行的末尾添加“姓氏”。 可以在Perl,sedawkgrep中执行此操作吗? 转换后的文件如下所示:

....
sth
Q-[N1] your name? **Jim**
A1-My first name is Joe
A2-My Last name is  Jim
sth
sth
....
....
sth
Q-[N2] your name? **JUNE**
A1-My first name is Jack
A2-My Last name is  JUNE
sth
sth
....

4 个答案:

答案 0 :(得分:1)

此解决方案实际上并不使用多行模式,而只查找第一行(Q-... your name?部分)并将后两行加载到模式空间中。然后用简单的正则表达式对这个(三行)模式空间进行一些替换,以获得所需的输出。

sed '/^Q-\[N[[:digit:]]*\] your name?/ {
  N
  N
  s/\( your name?\)\(.* Last name is *\)\(.*\)$/\1 **\3**\2\3/
}' < file

答案 1 :(得分:1)

use strict;
use warnings 'all';

our @ARGV = 'name_is_joe.txt';

my $data = do {
    local $/;
    <>; 
};

$data =~ s/^(Q-.+)(\n^A1-.+\n^A2-.+\bis\s+(.+)\n)/$1 $3$2/gm;

print $data

输出

....
sth
Q-[N1] your name? Jim 
A1-My first name is Joe
A2-My Last name is  Jim
sth
sth
....
....
sth
Q-[N2] your name? JUNE 
A1-My first name is Jack
A2-My Last name is  JUNE
sth
sth
....

或作为单行

perl -0777 -pe 's/^(Q-.+)(\n^A1-.+\n^A2-.+\bis\s+(.+)\n)/$1 $3$2/gm' myfile

答案 2 :(得分:0)

awk救援! (用tac)

$ tac file | 
  awk '/My Last name is/{n=$NF} /^Q-/{$0=$0 FS "**"n"**"}1' | 
  tac

....
sth
Q-[N1] your name? **Jim**
A1-My first name is Joe
A2-My Last name is  Jim
sth
sth
....
....
sth
Q-[N2] your name? **JUNE**
A1-My first name is Jack
A2-My Last name is  JUNE
sth
sth
....

答案 3 :(得分:0)

您可以先将换行符翻译为;,然后进行搜索和替换;最后将;翻译回换行符。请尝试:

cat temp | tr '\n' ';' | sed -r 's/(your\s+name\?)(;A1-[^-]*-My\s+Last\s+name\s+is\s+)(\w+)/\1 \3\2\3/g' | tr ';' '\n'

输出:

....
sth
Q-[N1] your name? Jim
A1-My first name is Joe
A2-My Last name is  Jim
sth
sth
....
....
sth
Q-[N2] your name? JUNE
A1-My first name is Jack
A2-My Last name is  JUNE
sth
sth
....