简体   繁体   English

Bash脚本中的SED可将变量的内容复制到文件中

[英]SED in Bash Script to copy the content of variable in a file

I need to copy the content of a variable in the top of other file without deleting the text of the file. 我需要在其他文件的顶部复制变量的内容,而不删除文件的文本。

I have this code: 我有以下代码:

var=$(<file.txt)
sed -i -e '1i$var' file2

But only writes the text "$var" in the first line of file2, not the total content of var. 但是仅在file2的第一行中写入文本“ $ var”,而不是var的总内容。

Any idea?. 任何想法?。

Thank you. 谢谢。

Use double quotes for shell to expand variables: 对外壳使用双引号扩展变量:

sed -i -e "1i$var" file2

btw you can avoid sed by using: 顺便说一句,您可以使用以下方法避免sed:

cat file.txt file2 > _tmp && mv _tmp file2

如果要在变量或多个变量后添加一些固定值,则必须在表达式周围使用双引号 ,在var周围使用大括号

sed -i "1s/^/${var}FIXEDTEXTHERE /" file2
cat file.txt <> file2

没有临时文件

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM