1

I'm using Ubuntu and I need to generate multiple .txt files from a large .txt file that contains a word in each new line.

Steps:

  1. Take one word from the large .txt list, e.g. foo
  2. generate .txt and name it [word].txt, e.g. foo.txt
  3. [word].txt should contain only the [word], e.g. foo.txt >contains foo text inside

I found that you can generate a .txt from the command line like this:

echo 'Hello, world.' >foo.txt 

How to do that in batch with the content from the large .txt file?

  • Please do not use comments to expand the question or to ask follow up questions. If you need to handle "multiple words in one line that contains spaces" then it should be stated in the question itself instead of "a word in each new line" (the two descriptions contradict each other). If you want to know how to "launch the bash script by double clicking it", ask a new question (after searching and researching, there may be a duplicate already answered). – Kamil Maciorowski Sep 16 '19 at 6:44
2

Something like this should work, but it doesn't check to make sure that the created filenames are legal. Also, if you have dupes, they will be overwritten:

#!/bin/bash

filename=/path/to/your_data_file
while read -r line
do
    echo $line > "$line.txt"
done < "$filename"
echo
  • Works great for single words, thank you. I ran into an additional question: How to handle multiple words in one line that contains spaces? e.g.: This Red Wall This returns an error: bash: $line.txt: ambiguous redirect – Tom Sep 14 '19 at 19:15
  • 1
    Good catch! I fixed my answer. – ajgringo619 Sep 14 '19 at 19:20
1

This answer is to correct common flaws that are present in other answers. Basic code should be like:

#!/bin/bash
filename="/path/to/your_data_file"

while IFS= read -r line
do
    printf '%s\n' "$line" > "$line.txt"
done < "$filename"

Improvements:

Some of them may not be strictly necessary if your_data_file really contains "a word in each new line" as stated in the question body. But your comment mentions handling "multiple words in one line that contains spaces", this requires non-robust solutions to be improved. It's better to get used to good practices in shell scripting and to write robust code from the start.

1

This might be a lot quicker for a large file...

#!/bin/bash

filename=/path/to/your_data_file

sort -u "$filename" | 
( IFS=
  while read -r line
  do
      echo $line > "$line.txt"
  done
)
  • Thanks for your suggestion. I would like to launch the bash script by double clicking it. How to do that? – Tom Sep 15 '19 at 14:04
  • Please enter a new question if you have a new subject. I believe that ^-- already has an answer too. Use Google or Superuser search. – Hannu Sep 16 '19 at 15:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.