将版权信息插入多个文件

Nic*_*ilt 8 unix shell scripting

您如何在每个文件的最顶部插入版权信息?

Pau*_*sey 12

#!/bin/bash
for file in *; do
  echo "Copyright" > tempfile;
  cat $file >> tempfile;
  mv tempfile $file;
done
Run Code Online (Sandbox Code Playgroud)

递归解决方案(查找.txt所有子目录中的所有文件):

#!/bin/bash
for file in $(find . -type f -name \*.txt); do
  echo "Copyright" > copyright-file.txt;
  echo "" >> copyright-file.txt;
  cat $file >> copyright-file.txt;
  mv copyright-file.txt $file;
done
Run Code Online (Sandbox Code Playgroud)

谨慎使用; 如果文件名中存在空格,则可能会出现意外行为.


gho*_*g74 5

SED

echo "Copyright" > tempfile
sed -i.bak "1i $(<tempfile)"  file*
Run Code Online (Sandbox Code Playgroud)

或壳

#!/bin/bash
shopt -s nullglob     
for file in *; do
  if [ -f "$file" ];then
    echo "Copyright" > tempfile
    cat "$file" >> tempfile;
    mv tempfile "$file";
  fi
done
Run Code Online (Sandbox Code Playgroud)

如果你有bash 4.0那么递归

#!/bin/bash
shopt -s nullglob
shopt -s globstar
for file in /path/**
do
      if [ -f "$file" ];then
        echo "Copyright" > tempfile
        cat "$file" >> tempfile;
        mv tempfile "$file";
      fi 
done
Run Code Online (Sandbox Code Playgroud)

或使用 find

find /path -type f  | while read -r file
do
  echo "Copyright" > tempfile
  cat "$file" >> tempfile;
  mv tempfile "$file";
done
Run Code Online (Sandbox Code Playgroud)