简体   繁体   中英

Bash get lines from text file by reading line numbers from another file

I have a file lines.txt of the following type:

1
3
5
6

And I have another file text.txt of the following type:

A
B
C
D
E
F
G
H

I want to get an output file containing:

A
C
E
F

Is there any bash command which would help me do that?

You can number the lines from text.txt by cat -n . Then you can use join to pair the two files based on the numbers, -o2.2 means show the second column from the second file .

cat -n text.txt | join -o2.2 lines.txt -

plan

  • use nl utility to number the lines
  • use join to join based on line number key

example

join -o 1.2 <( nl -n ln text.txt ) lines.txt

output

A
C
E
F

You can loop over the line numbers in lines.txt and then use sed the required lines:

for line in `cat lines.txt`
do
  sed -n "${line}p" text.txt
done

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM