首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在perl中获取第n行,其中n可以是四个整数。

在perl中获取第n行,其中n可以是四个整数。
EN

Stack Overflow用户
提问于 2013-09-23 18:10:23
回答 4查看 182关注 0票数 1

我想使用Perl从文件中提取四行。我有四个整数变量;例如:

代码语言:javascript
复制
a= 5;
b = 45;
c=30;
d=8;

是否可以从与这些值相对应的文件(即第5行、第45行、第30行、第8行)获取和存储四个字符串的行号?我一直在玩

代码语言:javascript
复制
-ne 'print if($.==5)';

但还有什么更有说服力的方法吗?这似乎是在检查我目前的线路.

EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2013-09-23 18:29:52

如果您希望它是一个一行,那么使用散列可以使它变得非常简单:

代码语言:javascript
复制
perl -ne '%lines = map { $_ => 1 } 23, 45, 78, 3; print if exists $lines{$.}' test.txt 

这将创建一个类似于( 23 => 1, 45 => 1, 78 => 1, 3 => 1 )的散列,然后使用exists检查当前行号是否是哈希中的一个键。

票数 6
EN

Stack Overflow用户

发布于 2013-09-23 18:39:09

如果您正在处理一个小文件,并且有足够的内存将内容读入脚本中,您可以将该文件放入数组中,然后以数组元素的形式访问这些行:

代码语言:javascript
复制
# 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:

代码语言:javascript
复制
awk 'NR==5' file.txt
sed -n '5p' file.txt
票数 4
EN

Stack Overflow用户

发布于 2013-09-23 20:15:40

一衬垫

代码语言:javascript
复制
 perl -ne 'print if ( $. =~ /^45$|^30$|^8$|^5$/  )' file.txt
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/18965976

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档