2017-03-09 11 views
0

ヘルプが必要です。私は一日を探して、私が必要とするものに特有の解決策を見つけられませんでした。文字列に基づいてファイル内の行を検索して削除しますが、最後の文字は残してください

ファイルで:

Lots 
of 
other 
lines 
... 
... 
# [email protected] ..........1323 <- Do not include '# Client=HOSTNAME' 
# [email protected] ..........123123 <- Do not include '# Client=HOSTNAME' 
[email protected] ....rndChars.... <- delete line 
[email protected] ....rndChars.... <- delete line 
[email protected] ....rndChars.... <- delete line 
[email protected] ....rndChars.... <- delete line 
[email protected] ....rndChars.... <- keep last occurrence 
[email protected] ....rndChars.... <- keep last occurrence 
[email protected] ....rndChars.... <- delete line 
[email protected] ....rndChars.... <- delete line 
[email protected] ....rndChars.... <- keep last occurrence 
... 
... 
more 
lines 

私は「クライアント=」以上に一致するすべての行を検索し、最後れる発生を除き行を削除する必要があります。問題は、私はホスト名がどうなるか分からない。

出力は次のようになります。事前に

Lots 
of 
other 
lines 
... 
... 
# [email protected] ..........1323 <- Do not include '# Client=HOSTNAME' 
# [email protected] ..........123123 <- Do not include '# Client=HOSTNAME' 
[email protected] ....rndChars.... <- keep last occurrence 
[email protected] ....rndChars.... <- keep last occurrence 
[email protected] ....rndChars.... <- keep last occurrence 
... 
... 
more 
lines 

Thxを。

+0

? –

答えて

0

救助者へのPerl。ファイルを2回読み込み、ホストごとに最後の行番号をハッシュテーブルに保存します。

#!/usr/bin/perl 
use warnings; 
use strict; 

my $client_re = qr/Client=(.*?)@/; 

my $filename = shift; 

open my $IN, '<', $filename or die $!; 

my %lines; 
while(<$IN>) { 
    next if /^#/; 

    # Overwrite the line number if already present. 
    $lines{$1} = $. if /$client_re/; 
} 

seek $IN, 0, 0; # Rewind the file handle. 
$. = 0;   # Restart the line counter. 
while (<$IN>) { 
    if (! /^#/ && (my ($hostname) = /$client_re/)) { 
     print if $lines{$hostname} == $.; # Only print the stored line. 
    } else { 
     print; 
    } 
} 
0

tac & awkを使用する:

tac file | awk '/^Client/{ if(!a[$1]){a[$1]++;print};next}1' | tac 

出力:あなたがこれまでに試してみました何

$ tac file | awk '/^Client/{ if(!a[$1]){a[$1]++;print};next}1' | tac 
Lots 
of 
other 
lines 
... 
... 
# [email protected] ..........1323 <- Do not include '# Client=HOSTNAME' 
# [email protected] ..........123123 <- Do not include '# Client=HOSTNAME' 
[email protected] ....rndChars.... <- keep last occurrence 
[email protected] ....rndChars.... <- keep last occurrence 
[email protected] ....rndChars.... <- keep last occurrence 
... 
... 
more 
lines 
0
sed -r ':a;N;$!ba;:b;s/(.*)(Client=[^@]+\b)[^\n]+\n*(.*\2)/\1\3/;tb' file 
関連する問題