如何使用一个已更改的字符串复制段落

如何使用一个已更改的字符串复制段落

我正在寻找可以复制段落、更改用户并将其插入同一文件中的东西。

之前的文件:

user1
  this is only
  a test of 
  a lovely idea

user2
  this user shhould
  be copied

user3
  who has an
  idea for
  my problem

之后的文件(user2被搜索、复制并插入为user4):

user1
  this is only
  a test of 
  a lovely idea

user2
  this user shhould
  be copied

user3
  who has an
  idea for
  my problem

user4
  this user shhould
  be copied

答案1

#!/bin/perl
#
use strict;

local $/="\n\n";

my $match = shift @ARGV;
my $subst = shift @ARGV;
my $save;

while (defined (my $paragraph = <>))
{
    $paragraph =~ s/\n+$//;
    $paragraph .= "\n";

    my $user = ($paragraph =~ m/(\w+)\n/)[0];
    if ($match eq $user)
    {
        $save = $paragraph;
        $save =~ s/\b$user\b/$subst/g
    };

    print "$paragraph\n"
}
print "$save" if defined $save;
exit 0

像这样使用它

script.pl user2 user4 <file

答案2

解决方案在TXR

@(collect)
@name
@  (collect)
@line
@  (last)

@  (end)
@  (maybe)
@    (bind name @[*args* 1])
@    (bind cname @[*args* 2])
@    (bind cline line)
@  (end)
@(end)
@(merge name name cname)
@(merge line line cline)
@(output)
@  (repeat)
@name
@    (repeat)
@line
@    (end)

@  (end)
@(end)

跑步:

$ txr insert.txr data user2 user4
user1
  this is only
  a test of
  a lovely idea

user2
  this user shhould
  be copied

user3
  who has an
  idea for
  my problem

user4
  this user shhould
  be copied

awk 状态机:

BEGIN       { split(ed,kv,","); }
1
$0 ~ kv[1]  { copy = 1; next }
copy        { lines = lines ? lines "\n" $0 : $0 }
/^$/        { if (copy) have = 1; copy = 0; }
END         { if (have) { print ""; print kv[2] ; print lines } }

运行(输出如前):

$ awk -f insert.awk -v ed=user2,user4 data
user1
  this is only
  a test of
  a lovely idea

user2
  this user shhould
  be copied

user3
  who has an
  idea for
  my problem

user4
  this user shhould
  be copied

TXR Awk,等效逻辑。行是在实际的列表数据结构中累积的,而不是字符串。该列表充当布尔值,如果不为空则表示 true,因此我们不需要该have标志。我们可以直接访问数据文件后的剩余参数。

(awk
  (:inputs [*args* 0])
  (:let lines copy)
  (t)
  ((equal rec [*args* 1]) (set copy t) (next))
  (copy (push rec lines))
  ((equal rec "") (set copy nil))
  (:end (when lines
          (put-line) (put-line [*args* 2]) (tprint (nreverse lines)))))

运行(输出如前):

$ txr insert.tl data user2 user4

相关内容