Results 1 to 5 of 5
Hi
I have 1 file which i want to copy its contents into 30 other files without changing any of the file names. these are just normal txt files. for ...
- 12-09-2008 #1Just Joined!
- Join Date
- Dec 2008
- Posts
- 2
Copy contents of 1 file into many
Hi
I have 1 file which i want to copy its contents into 30 other files without changing any of the file names. these are just normal txt files. for examples sake, i will explain the file names.
the file i want to copy is called "source.txt"
the 30 files that i want to change the contents of all begin with file1 and goes all the way up to 30 e.g. "file1.txt ...... file30.txt"
i tried to use the cat command with redirection " cat source.txt > flle*" but it didn't work...
- 12-09-2008 #2Linux User
- Join Date
- Jun 2007
- Posts
- 318
You can't use a glob (the asterisk '*') in the destination. You have to use the find command to find each file you want to copy source.txt to and execute the cp (copy) command instead of cat for each one.
Code:find . -type f -maxdepth 1 \( -name "file[1-9].txt" -o -name "file[1-3][0-9].txt" \) -exec cp source.txt {} \;
- 12-09-2008 #3Just Joined!
- Join Date
- Dec 2008
- Posts
- 2
Thanks for the reply
just out of interest, is there a way in which i can remove the file name bit from the code and just use a wildcard e.g.
instead of this:
...( -name "file[1-9].txt" -o -name "file[1-3][0-9].txt" \....
use somethings like this:
...."*.txt"
- 12-09-2008 #4Linux User
- Join Date
- Jun 2007
- Posts
- 318
- 12-11-2008 #5Just Joined!
- Join Date
- Nov 2008
- Posts
- 4
vsemaska's solution looks fine, and it's hard-core unix.
If you have to do this operation more often, and don't enjoy a lot of typing (or can't remember the syntax) a script may suit you better.
SUGGESTED FORMAT: "yourScript sourceFile globPattern"
In globPattern you can use the usual * ? [chars2match] [^not2match]
My favorite scripting language is python, so here you go:
COMMENTS:Code:#!/usr/bin/env python # or '#!/bin/env python' import os, sys for fname in sys.argv[2:]: if sys.argv[1] == fname: continue os.system("cp %s %s" % (sys.argv[1], fname))
One of the advantages of using a script, or even a high-level scripting language, it's easy to expand,Code:Use the sha-bang line '#!...' that works on your system sys.argv[1] is the 1st argument (source file) sys.argv[2:] are the remainig arguments (target files) os.system(...) executes a (shell) command %s is used for string repacement The line 'if sys.argv[1] == fname: continue' excludes the source
like above condition ' if sys.argv[1] == fname: continue' (which means ignore source).
If you need to put all the functionality you want into one cmd line you have to tinker quiet a bit to make it work, and you get only little help from the cmd line. In contrast, with a high-level language you get detailed exceptions of what you are doing wrong.


Reply With Quote
