如何用另一个文件替换目录中所有文件的内容?

时间:2012-02-06 18:01:53

标签: file bash replace

我正在尝试编写一个简单的bash脚本,用一个新文件替换目录中的所有文件,但保留要替换的每个文件的名称。

看起来这应该很容易,所以如果这很明显我会提前道歉。

5 个答案:

答案 0 :(得分:3)

由于您只需要新文件的内容但保持文件名相同,因此您可以使用cat一步完成此操作。

以下两个脚本以递归方式和任何文件名工作,即使是那些包含空格或换行符的脚本,也可能是在您尝试解析ls输出时可能会中断的其他脚本。

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

答案 1 :(得分:2)

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

答案 2 :(得分:0)

试试这个:

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

答案 3 :(得分:0)

如果你安装了GNU Parallel:

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

如果你在一个只包含文件(没有dirs)的目录中,那么这个更短,也许更容易记住:

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

它正确处理包含空格的文件'和'(对于包含换行符的文件名,您需要上述内容。)

您可以通过以下方式安装GNU Parallel:

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

观看介绍视频以了解详情:http://pi.dk/1

答案 4 :(得分:-1)

#!/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/)"

您可能会计划在代码示例中更改/ directory / backup和/ new / replacement。 您可以使用“find”而不是“ls”来递归。 它现在不会出现空间问题。

相关问题