bash Shell脚本将文本附加到每个文件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5586293/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 20:23:27  来源:igfitidea点击:

Shell script to append text to each file?

bashconcatenation

提问by Steve

I have a folder full of text files. I need to append the same block of text to each of them (and of course overwrite the original file).

我有一个装满文本文件的文件夹。我需要将相同的文本块附加到每个文件中(当然还需要覆盖原始文件)。

I was wondering what the correct Bash shell syntax would be for this. Would I use cat?

我想知道正确的 Bash shell 语法是什么。我会用猫吗?

I have done a few batch scripts but I'm not a Bash expert. Any suggestions appreciated.

我已经完成了一些批处理脚本,但我不是 Bash 专家。任何建议表示赞赏。

回答by Ignacio Vazquez-Abrams

Use append redirection.

使用附加重定向。

for f in *.txt
do
  cat footer >> "$f"
done

回答by GreenMatt

If you're needing to do this via a script, you can use echo and append redirection to get the extra text into the files.

如果您需要通过脚本执行此操作,您可以使用 echo 和 append 重定向将额外的文本放入文件中。

FILES=pathto/*
for f in $FILES ; do
    echo "#extra text" >> $f
done

回答by kurumi

sed -i.bak "$ a $(<file_block_of_text)" *.txt

回答by Joe Corneli

Variant of kurumi's answer:

kurumi 答案的变体:

sed -i.bak "$aTEXTTOINSERT" *.txt

For more details, see SED: insert something to the last line?

有关更多详细信息,请参阅SED:在最后一行插入内容?