4

I have a WINDOWS text file that contains the following in its own directory: It is called "test.txt"

Example Source File - test.txt:

hxxp://url.xxx/XX/file 1.txt
hxxp://url.xxx/XX/file 2.avi
hxxp://url.xxx/XX/file 3.mpg

The content of the first file would be:

hxxp://url.xxx/file 1.txt

The name of this file would be:

file 1.txt

My goal is to create separate text files containing each URL and named after the "file" part of the URL. So the first one would be "file 1.txt.txt" then "file 2.avi.avi" and so on. Split does this perfectly EXCEPT for naming the actual files.

5

This is easily done in awk. You just need to set the field separator to / and then print each line into a file whose name is the last field. Since the number of fields in awk is saved in the NF variable, you can get the last fields with $NF. Then, if you want all of them to have the txt extension, all you need is:

awk -F'/' '{print > $NF".txt"}' file 

If, as seems to be the case based on your comments, your input file has Windows line endings, you need to remove the \r first:

sed 's/\r//' file | awk -F'/' '{print > $NF".txt"}' 
  • I tried this and it worked for file 3. But for the other files it made some nonsensical files: FEI1YX~E and FSVB57~1 – Aaron Mar 29 '17 at 20:16
  • @Aaron then your input is not like what you show in your question. Edit your question and include an actual example that fails please. – terdon Mar 29 '17 at 20:25
  • Thanks for helping terdon. I apologize if I wasn't clear. I have a text file that contains exactly those sample urls in its own directory. It is called "test.txt" I then ran your command replacing "file" with "test.txt". Three new files were created. "file 3.mpg" and those other ones I already mentioned. My goal is to create text files containing each URL and named after the field with a ".txt" ending. So the first one would be "file 1.txt.txt" then "file 2.avi.txt" and so on. Split does this perfectly EXCEPT for naming the actual files. – Aaron Mar 29 '17 at 20:31
  • @Aaron oh. Then please edit your question and clarify. By the way, you know that there is absolutely no reason to have any extension for a trext file, right? I mean foo, foo.txt and foo.bar are treated no differently on *nix systems. – terdon Mar 29 '17 at 20:34
  • @Aaron also, see update. If you really want that, just add .txt. – terdon Mar 29 '17 at 20:35

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.