1

Perl を使用してファイルから 4 行を取得したいと考えています。4 つの整数変数があります。例えば:

a= 5;
b = 45;
c=30;
d=8;

これらの値に対応するファイルの行番号 (5 行目、45 行目、30 行目、8 行目) を 4 つの文字列として取得して保存することはできますか? 私は遊んでいます

-ne 'print if($.==5)';

しかし、もっと雄弁な方法はありますか?これは、現在どの行にいるのかを確認しているようです...

4

4 に答える 4

6

ワンライナーにしたい場合は、ハッシュを使用すると非常に簡単になります。

perl -ne '%lines = map { $_ => 1 } 23, 45, 78, 3; print if exists $lines{$.}' test.txt 

これにより、次のようなハッシュが作成され、現在の行番号がハッシュのキーであるかどうかを確認するため( 23 => 1, 45 => 1, 78 => 1, 3 => 1 )に使用されます。exists

于 2013-09-23T18:29:52.517 に答える
4

小さなファイルで作業していて、コンテンツをスクリプトに丸呑みするメモリがある場合は、ファイルを配列に丸呑みしてから、配列要素として行にアクセスできます。

# define the lines you want to capture
$a=5;
$b=45;
$c=30;
$d=8;

# slurp the file into an array
@file = <>;

# push the contents of the array back by one
# so that the line numbers are what you expect
# (otherwise you would have to add 1 to get the
# line you are looking for)
unshift (@file, "");

# access the desired lines directly as array elements
print $file[$a];
print $file[$b];
print $file[$c];
print $file[$d];

コマンドラインのワンライナーを探している場合は、awk または sed を試すこともできます。

awk 'NR==5' file.txt
sed -n '5p' file.txt
于 2013-09-23T18:39:09.680 に答える
2

一発ギャグ

 perl -ne 'print if ( $. =~ /^45$|^30$|^8$|^5$/  )' file.txt
于 2013-09-23T20:15:40.480 に答える