提取文件unix的多行 [英] extract multiple lines of a file unix

查看:84
本文介绍了提取文件unix的多行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含40万行的文件A。我有另一个文件B,它有一堆行号。

I have a file A with 400,000 lines. I have another file B that has a bunch of line numbers.

File B:  
-------
98  
101
25012
10098
23489

我必须提取指定的行号是从文件A中提取文件B。也就是说,我要从文件A中提取行98,101,25012,10098,23489。在以下情况下如何提取这些行。

I have to extract those line numbers specified in file B from file A. That is I want to extract lines 98,101,25012,10098,23489 from file A. How to extract these lines in the following cases.


  1. 文件B是一个显式文件。

  2. 文件B从管道中移出。例如,grep -n pattern somefile.txt给我文件B。

我想使用-n'x 'p fileA。但是,我不知道如何从文件中给出 x。另外,我也不会介绍如何通过命令传递 x的值。

I wanted to use see -n 'x'p fileA. However, I don't know how to give the 'x' from a file. Also, I don't to how to pipe the value of 'x' from a command.

推荐答案

sed 可以打印所需的行号:

sed can print the line numbers you want:

$ printf $'foo\nbar\nbaz\n' | sed -ne '2p'
bar

如果需要多行:

$ printf $'foo\nbar\nbaz\n' | sed -ne '2p;3p'
bar
baz

要转换a这样的 sed 命令的行集,将 sed 用作漂亮的 sed ception:

To transform a set of lines to a sed command like this, use sed for beautiful sedception:

$ printf $'98\n101' | sed -e 's/$/;/'
98;
101;

放在一起:

sed -ne "$(sed -e 's/$/p;/' B)" A

测试:

$ cat A
1
22
333
4444
$ cat B
1
3
$ sed -ne "$(sed -e 's/$/p;/' B)" A
1
333

QED。

这篇关于提取文件unix的多行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆