将多个文本块提取到新文件

时间:2017-09-01 22:12:45

标签: linux bash awk sed

我需要帮助从单个文本文件中将信息块提取到新文件或某些形式,我可以从每个块中操作数据。

示例:

[Block1]
this=that
here=there
why=why_not

[Block2]
this=those
here=there
why=because

我需要能够显示和/或操纵变量(如果我可以隔离正确的变量,我可以这样做)。我不介意将每个块写入临时文件

那么,我如何仅在here=there中将here=anywhere更改为Block2

我试图用sed / awk解决这个问题,但没有用。

5 个答案:

答案 0 :(得分:4)

使用sed:

sed '/^\[Block2\]/,/^$/s/here=there/here=anywhere/' file
  • /^\[Block2\]/,/^$/:从[Block2]开始到下一个空行(^$)或文件结尾之间......
  • s/here=there/here=anywhere/:将here=there替换为here=anywhere

答案 1 :(得分:1)

这会将您的文件拆分为名为block1,block2等的文件,并对Block2进行更改,并且可以在任何UNIX框上使用任何awk:

awk -v RS= -F'\n' '
{
    close(out)
    out = "block" NR
    if ($1 == "[Block2]") {
        sub(/here=there/,"here=anywhere")
    }
    print > out
}
' file

使用GNU awk它甚至更简洁:

awk -vRS= -F'\n' '$1=="[Block2]"{sub(/here=there/,"here=anywhere")} {print>("block"NR)}' file

答案 2 :(得分:0)

使用Perl的可能解决方案:

perl -00 -pe '/^\[Block2\]\n/ or next; s/^here=there$/here=anywhere/m'

-p告诉perl将代码包装在隐式输入/输出循环中(类似于sed)。

-00告诉perl以段落(而不是行)为单位处理输入。

-e ...指定程序。我们首先确保段落以[Block2]开头(否则我们会跳过所有其他处理)。然后,我们将here=there形式的行替换为here=anywhere

答案 3 :(得分:0)

我使用Config::IniFiles Perl模块。如果您在RedHat或Centos系统上运行,请尝试:

$ sudo yum install perl-Config-IniFiles

对于Ubuntu使用apt-get ...

以下是Config :: IniFile概要中示例脚本的修改版本:

$ cat syn.pl
#!/bin/perl -w

use strict;

use Config::IniFiles;
my $cfg = Config::IniFiles->new( -file => "./inifile.ini" );
print "The value is " . $cfg->val( 'Block2', 'here' ) . ".\n"
    if $cfg->val( 'Block2', 'here' );

以下是一个示例运行:

$ cat inifile.ini
[Block1]
this=that
here=there
why=why_not

[Block2]
this=those
here=there
why=because
$ ./syn.pl
The value is there.

here中更改Block2非常简单:

$ cat rewrite.pl
#!/bin/perl -w

use strict;

use Config::IniFiles;
my $cfg = Config::IniFiles->new( -file => "./inifile.ini" );
print "The value is " . $cfg->val( 'Block2', 'here' ) . ".\n"
    if $cfg->val( 'Block2', 'here' );
$cfg->setval( 'Block2', 'here', 'anywhere' );
$cfg->RewriteConfig();
$ cat inifile.ini
[Block1]
this=that
here=there
why=why_not

[Block2]
this=those
here=there
why=because
$ ./rewrite.pl
The value is there.
$ cat inifile.ini
[Block1]
this=that
here=there
why=why_not

[Block2]
this=those
here=anywhere
why=because

答案 4 :(得分:0)

首先插入“here = anywhere”,然后删除doublet。

awk '/this=those/{print;print "here=anywhere";next}!($0 in a) {a[$0];print}' file

[Block1]
this=that
here=there
why=why_not

[Block2]
this=those
here=anywhere
why=because