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

Solution 1:

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.

Solution 2:

The following one-liner will do what you need:

bash -c "$(paste text1.txt text2.txt | awk '{print "echo "$2">"$1".txt"}')"

Solution 3:

Another python option:

#!/usr/bin/env python3
import sys

lines = lambda f: open(f).read().splitlines()
content = lines(sys.argv[2])

for i, item in enumerate(lines(sys.argv[1])):
    open(item+".txt", "wt").write(content[i])

This will create the indicated files in the directory where you run the script from

  • Save it as combine.py
  • run it with the command:

    python3 /path/to/combine.py <file1> <file2>
    

Edit

As suggested by @queueoverflow, using the zip option (very neat, even shorter):

#!/usr/bin/env python3
import sys

lines = lambda f: open(f).read().splitlines()
for item, content in zip(lines(sys.argv[1]), lines(sys.argv[2])):
    open(item+".txt", "wt").write(content)

OR

Just for fun; including the sys.argv[n] in the lambda function, reducing it a bit further:

#!/usr/bin/env python3
import sys

lines = lambda n: open(sys.argv[n]).read().splitlines()
[open(f+".txt", "wt").write(c) for f, c in list(zip(lines(1), lines(2)))]

Solution 4:

That worked for me:

c=1; while read f; do sed -n "${c}p" text2.txt >"$f.txt"; ((c++)); done <text1.txt

It iterates trough every line in the file text1.txt. Then for every line sed extracts the corresponding line in the file text2.txt and writes it to the that file with .txt appended.