Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/search/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在bash/perl中解析txt文件的有效方法_Bash_Perl_Awk_Sed - Fatal编程技术网

在bash/perl中解析txt文件的有效方法

在bash/perl中解析txt文件的有效方法,bash,perl,awk,sed,Bash,Perl,Awk,Sed,我有无数大小为300k+行的文本文件 这些文件采用以下通用格式: Username <user> filename <file> <some large amount of text on one line> ... 基本上,是否有一些有效的方法来检测我正在寻找的字符串,然后返回x行数(x对应于页眉行数),然后提取我需要的信息? 谢谢 PS在bash-perl中也没有这样做 编辑:所需的输出 <user>, <file> <

我有无数大小为300k+行的文本文件

这些文件采用以下通用格式:

Username <user> filename <file>
<some large amount of text on one line>
...
基本上,是否有一些有效的方法来检测我正在寻找的字符串,然后返回x行数(x对应于页眉行数),然后提取我需要的信息? 谢谢

PS在bash-perl中也没有这样做

编辑:所需的输出

 <user>, <file>
 <user>, <file>
 ...
,
, 
...

对于这种非常繁重的文本处理,perl是一个不错的选择:

perl -nE '
  if ($. % 2 == 1) {
    ($user, $file) = (split ' ')[1,3];
  } 
  elsif (/search string/) {
    say "$user, $file";
  }
' file1 file2 ...

如果您喜欢,可以将其“简化”为更简洁的单行线。

Awk解决方案,依赖于每条记录有两行(文件的第一行是第一条记录的标题):


用户名
行和要匹配的行之间是否有固定数量的
行?你能不能也包括一些匹配什么和不匹配什么的示例数据?我做了一个小编辑-让我们假设只有一个标题行,匹配的字符串真的不重要。。。重要的是要知道它与一些
$string
@user3979986:这太模糊了!如果紧跟其后的行与任何
$string
匹配,则需要打印
用户
文件
字段。意思是任意一个随机字符串?真奇怪。解释这一点的方法是给出一个简短的输入示例,其中包括一些打印的
用户
文件
值和一些未打印的值。即使是一个完整的shell脚本工作版本也会有很大的帮助。任何时候你在shell中编写一个循环只是为了转换文本,你的方法都是错误的。显示一些实际的示例输入,而不仅仅是输入格式的描述,以及给定该输入的所需输出。您的示例输入行不需要“非常长”来演示您的问题。
perl -nE '
  if ($. % 2 == 1) {
    ($user, $file) = (split ' ')[1,3];
  } 
  elsif (/search string/) {
    say "$user, $file";
  }
' file1 file2 ...
NR%2 { name = $2; file =$4; next }
/string/ { print name, file }