0

I have have a text file with many lines like this:

Smith: ''Handbook of Everything.'' Fantasy Press, 2000.
Wilson: ''Unix for Dummies.'' Wiley, 1993.

I want to write every line into a new file. The new file should contain the whole line and should be named same to the line it contains.

Smith: ''Handbook of Everything.'' Fantasy Press, 2000.txt
Wilson: ''Unix for Dummies.'' Wiley, 1993.txt

How do I accomplish this? Thanks.

αғsнιη
  • 40,939
  • 15
  • 71
  • 114
lejonet
  • 103
  • 4

3 Answers3

4

Using awk:

awk '{ fname=$0 "txt"; print > fname; close(fname) }' file
αғsнιη
  • 40,939
  • 15
  • 71
  • 114
Freddy
  • 25,172
  • 1
  • 21
  • 60
2

If your textfile is called textfile, the following should do the job

while read -r x
do
    echo "$x" > "${x}txt"
done < textfile
αғsнιη
  • 40,939
  • 15
  • 71
  • 114
unxnut
  • 5,908
  • 2
  • 19
  • 27
1

You can create a bash script as shown below. Replace /tmp/textFile.txt with the absolute path to your text file.

#!/bin/bash
file=/tmp/textFile.txt
while IFS= read -r line
do
        printf "%s\n" "$line" > /tmp/"$line"txt
done < "$file"
bit
  • 1,076
  • 2
  • 17
  • 36
  • 2
    Why the `touch` part? Note that there's nothing bash-specific in that script. It's standard `sh` syntax. – Stéphane Chazelas Dec 30 '20 at 13:42
  • Point taken. It's good to know this script is portable to other shells, and can be executed using zsh for example. – bit Jan 06 '21 at 23:33