0

How can I copy the file greetings.text and paste its contents into 1.txt, 2.txt, 3.txt, 4.txt and 5.txt?

$ cat greetings.text  
Hello  
Hello  
Hello  
Hello  
Hello  
  • @αғsнιη That will complain about missing {1..4}.txt and 5.txt not being a directory. – PerlDuck Oct 9 '18 at 17:47
  • I don't understand all the down voting on this question, it's not a complicated question, but it's not invalid or anything. Amateurish maybe, but on it's own, that's not a bad thing. – tommy61157 Oct 11 '18 at 14:20
  • @tommy61157 didn't downvote, but usually questions that do not express any effort to find out are not really appreciated. Don't really agree with the close votes though. We have numerous questions on text processing, always on topic. – Jacob Vlijm Oct 11 '18 at 14:25
8

You can use tee:

< greetings.text tee {1..5}.txt

Use tee -a if you wish to append to the files rather than overwrite them.

  • 1
    i am using that but it says no such file or directory !!! – Kaniwar Hanan Oct 8 '18 at 19:19
  • ~/shell$ cat greetings.text Hello Hello Hello Hello Hello – Kaniwar Hanan Oct 8 '18 at 19:19
  • sorry, it's my mistake .i was distracted.. thanks for your help – Kaniwar Hanan Oct 8 '18 at 19:28
  • 3
    @steeldriver please note this comment that, this "has the defect of not preserving any file metadata" from Gilles about your answer also. – αғsнιη Oct 9 '18 at 18:10
  • Particularly if the file is large, you might want to add >/dev/null afterwards to prevent unnecessary terminal output. – Paddy Landau Oct 16 '18 at 11:19
2

Use

cat greetings.text | tee {1..5}.txt

or

for i in {1..5} ; do cp greetings.text $i.txt ; done
1

Use cp in a loop:

src=greetings.txt
for dst in {1..5}.txt; do
    cp -T -- "$src" "$dst"
done

If you add the --reflink option, cp will instruct the target file system to try to create a “shallow” copy of the files that only duplicates the data blocks when something modifies them. This technique is called copy-on-write.

  • `src=greetings.text' – Vijay Oct 12 '18 at 17:02
0

If the contents must remain the same (i.e., you don't mean to update the copied files), you can use soft or hard links:

for i in {00..05} ; do ln greetings.text $i.txt ; done

Copy is then instantaneous even with big files, and you won't use any additional disk space with the copies (I used that when I was performing tests with 200GB files). The file contents are available until the last of the copies+original is rm-ed.

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.