2016-01-21 27 views
-1

我想创建一个脚本,将文本(带有许多行)作为标题放在具有txt扩展名的多个文件中。但是要插入的文本需要放置将要插入的文件的文件名。使用bash添加一个带有一个可变数字的文本到多个文件

文本(待填)

abcdgd FILENAME dhsgabc shcnwk shfgamvk cjshjg nwdcbi skfh nwvjcnd

skfh dvwuv

我有很多的文件,名为001.txt,002。 txt,003.txt等等... SO NAMEFILE只需要001,002,003等等(不带.txt扩展名)

th anks

+1

cooooooooooooooooooool – 123

+0

到目前为止你做了什么? – Noproblem

+0

我不知道该怎么办?我是初学者 – alloppp

回答

0

这个脚本会创建一个新的组命名001.txt.new,002.txt.new文件......与变化,你要求:

# Create a re-usable header file: 
cat > header << @@ 
abcdgd FILENAME dhsgabc shcnwk shfgamvk cjshjg nwdcbi skfh nwvjcnd 
@@ 

# Loop over all files: 
for i in [0-9][0-9][0-9].txt; do 
    # Get file name without suffix: 
    NAME=$(echo $i|sed -r 's/(.*)\.txt/\1/' 

    # Create a new file containing the modified header line: 
    cat header | sed 's/FILENAME/'"$NAME"'/' > ${i}.out 

    # Append contents of the original file to the new file: 
    cat $i >> ${i}.out 
done 

如果你想完全取代原来的文件,你可以加入这一行循环的结尾:

mv ${i}.out $i 

但你可能会想替换它们之前备份的原始文件以某种方式。

相关问题