Ubuntu – Access individual lines of a text file and create separate text file with that name

command linetext processing

I have two text files (say text1.txt and text 2.txt) both with same number of lines.
Ex. text1.txt contains 4 entries

0127H
0132H
0982H
1772H

text2.txt contains 4 entries

stev
mary
beautiful
ugly

Now my task is to create 4 text files as

  • 0127H.txt to contain stev

  • 0132H.txt to contain mary

  • 0982H.txt to contain beautiful

  • 1772H.txt to contain ugly

I.e. the 1st line of text1.txt must be a file name and the corresponding entry will be the 1 st line of text2.txt.

I kindly request you to help me to get rid of the issue raised.

Best Answer

With awk, you can do:

awk 'FNR == NR {filename[FNR] = $0 ".txt"} FNR != NR {print > filename[FNR]}' file1 file2
  • FNR == NR tests whether we are reading the first file. If that's the case, we save the line in an array.
  • When we read the second file, we lookup the corresponding array value and use that as the output file.