我想使用Perl从文件中提取四行。我有四个整数变量;例如:
a= 5;
b = 45;
c=30;
d=8;是否可以从与这些值相对应的文件(即第5行、第45行、第30行、第8行)获取和存储四个字符串的行号?我一直在玩
-ne 'print if($.==5)';但还有什么更有说服力的方法吗?这似乎是在检查我目前的线路.
发布于 2013-09-23 18:29:52
如果您希望它是一个一行,那么使用散列可以使它变得非常简单:
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-23 18:39:09
如果您正在处理一个小文件,并且有足够的内存将内容读入脚本中,您可以将该文件放入数组中,然后以数组元素的形式访问这些行:
# 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-23 20:15:40
一衬垫
perl -ne 'print if ( $. =~ /^45$|^30$|^8$|^5$/ )' file.txthttps://stackoverflow.com/questions/18965976
复制相似问题