user1120422
user1120422

Reputation: 63

How can I replace the contents of all files in a directory with another file?

I'm trying to write a simple bash script that replaces all the files in a directory with a new file, but preserves the name of each file being replaced.

It seems like this should be easy, so my apologies in advance if this is obvious.

Upvotes: 3

Views: 969

Answers (5)

Ole Tange
Ole Tange

Reputation: 2025

If you have GNU Parallel installed:

find . -type f -print0 | parallel -0 cat /path/to/foo \> {}

If you are in a dir that only contains files (no dirs) then this is shorter and maybe easier to remember:

parallel cat /path/to/foo \> {} ::: *

It deals correctly with files containing space, ' and " (for filenames containing newline, you need the above).

You can install GNU Parallel simply by:

wget http://git.savannah.gnu.org/cgit/parallel.git/plain/src/parallel
chmod 755 parallel

Watch the intro videos to learn more: http://pi.dk/1

Upvotes: 0

sgibb
sgibb

Reputation: 25736

#!/bin/sh
for i in *; do
  if [ -f "${i}" ] ; then 
    cat /dev/null > "${i}";
  fi;
done

Upvotes: 2

John
John

Reputation: 7826

#!/bin/bash
while read name; do
 cp "/directory/$name" /backup/
 mv /new/replacement "/directory/$name"
 echo "replaced /directory/$name with /new/replacement and stored backup in /backup"
done <<< "$(ls -1 /directory/)"

you will likely plan to change /directory /backup and /new/replacement in the code example. You can use "find" instead of "ls" to do it recursive. It won't have problems with spaces now.

Upvotes: -1

SiegeX
SiegeX

Reputation: 140397

Since you just want the contents of the new file but keep the file names the same, you can do this in one step with cat.

The following two scripts work recursively and with any file name, even ones that contain spaces or newlines or whatever else might break if you tried to parse ls output.

Bash > 2.x

#!/bin/bash
newFile="/path/to/newFile"
while IFS= read -r -d '' file; do
  cat "$newFile" > "$file"
done < <(find . -type f -print0)

Bash 4.x

#!/bin/bash
newFile="/path/to/newFile"
shopt -s globstar
for file in **; do
  [[ -f "$file" ]] || continue
  cat "$newFile" > "$file"
done

Upvotes: 3

Fritz G. Mehner
Fritz G. Mehner

Reputation: 17198

Try this one:

for file in *; do
  if [ -f "$file" ] ; then
    > "$file"
  fi
done

Upvotes: 0

Related Questions