Kang Min Yoo
Kang Min Yoo

Reputation: 815

What is the most efficient (in terms of speed and number of lines) way to replace a file content by another file content in Bash?

File A (a.txt) contains integers in each line, where the integer ranges from 1 to K:

1
5
4
2
6
...

File B (b.txt) contains arbitrary strings in each line, and the number of lines is exactly K:

Sports
World
Finance
Politics
...

The goal here is to replace each line in a.txt by retrieving corresponding line index from b.txt.

Now if I were to use python to achieve this goal, I would construct a dictionary from b.txt and simply map each value in a.txt using the dictionary.

What would be the best way to achieve the same goal using Bash scripts?

Upvotes: 1

Views: 62

Answers (2)

thanasisp
thanasisp

Reputation: 5975

awk 'FNR==NR{a[NR]=$0;next} {print a[$0]}' file2 file1

This awk script first reads the file with the descriptions and store them in array, then parses the file with the numbers and prints the corresponding lines.

Upvotes: 2

larsks
larsks

Reputation: 311703

Read b.txt into an array with mapfile, then use the values in a.txt as indexes into that array.

# read b.txt into array b_data
mapfile b_data < b.txt

while read index; do
  echo "${b_data[index]}"
done < a.txt > new_a.txt

And then rename new_a.txt to a.txt if that's your goal.

Upvotes: 2

Related Questions