Linux 用字符串替换文本文件中的第一行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13438095/
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
Replace the first line in a text file by a string
提问by Rookie
I am a newbie at shell scripting, and am confused about how to use sed
or any other tools to replace the first line in my text file by a string. Here are the text file contents:
我是 shell 脚本的新手,对如何使用sed
或任何其他工具将文本文件中的第一行替换为字符串感到困惑。以下是文本文件内容:
/home/snehil/Desktop/j1/movie.MOV "spome other text lines'
I want to replace the first line (movie file path) with just movie.MOV
(could be a variable in the shell script)
我想用just movie.MOV
(可能是shell脚本中的变量)替换第一行(电影文件路径)
Please guide me how to do this. I came across sed
in some posts, do I need to use sed
here?
请指导我如何做到这一点。我sed
在一些帖子中遇到过,我需要在sed
这里使用吗?
采纳答案by Gilles Quenot
sed is the right tool, try doing :
sed 是正确的工具,请尝试执行以下操作:
var="movie.MOV"
sed -i "1s/.*/$var/" file.txt
explanations
解释
1
mean first line- the rest is the substitution
s///
: we substitute everything (.*) by the$var
variable
1
平均第一行- 剩下的就是替换
s///
:我们用$var
变量替换所有内容 (.*)