2010-03-15 22 views

回答

12
#!/bin/bash 
for file in *; do 
    echo "Copyright" > tempfile; 
    cat $file >> tempfile; 
    mv tempfile $file; 
done 

遞歸解決方案(發現所有子目錄中的所有文件.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 

要小心;如果文件名中存在空格,您可能會收到意外的行爲。

+0

+1對於他的下一個把戲,保羅將與'的perl -e做它在5個字節' – 2010-03-15 20:30:21

+0

+1好的!將進入我的工具庫。我想知道,如何使這個遞歸? – 2010-03-15 20:30:24

+0

@Byron Whitlock:爲什麼perl?對於遞歸,sed會做得很好 – 2010-03-15 20:36:17

0

你可以使用這個簡單的腳本

#!/bin/bash 

# Usage: script.sh file 

cat copyright.tpl $1 > tmp 
mv $1 $1.tmp # optional 
mv tmp $1 

文件列表可以通過find工具來管理

5

sed的

echo "Copyright" > tempfile 
sed -i.bak "1i $(<tempfile)" file* 

或殼

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

做遞歸,如果你有bas^h 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 

或使用find

find /path -type f | while read -r file 
do 
    echo "Copyright" > tempfile 
    cat "$file" >> tempfile; 
    mv tempfile "$file"; 
done 
+0

做得非常好。你在這裏介紹了很多技巧。我稍後會研究它們。謝謝。 – 2010-03-16 01:41:52

0

工作在Mac OSX上:

#!/usr/bin/env bash 

for f in `find . -iname "*.ts"`; do # just for *.ts files 
    echo -e "/*\n * My Company \n *\n * Copyright © 2018 MyCompany. All rights reserved.\n *\n *\n */" > tmpfile 
    cat $f >> tmpfile 
    mv tmpfile $f 
done