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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 17:49:06  来源:igfitidea点击:

Replace the first line in a text file by a string

linuxshellunix

提问by Rookie

I am a newbie at shell scripting, and am confused about how to use sedor 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 sedin some posts, do I need to use sedhere?

请指导我如何做到这一点。我sed在一些帖子中遇到过,我需要在sed这里使用吗?

采纳答案by Gilles Quenot

sed is the right tool, try doing :

sed 是正确的工具,请尝试执行以下操作:

var="movie.MOV"
sed -i "1s/.*/$var/" file.txt

explanations

解释

  • 1mean first line
  • the rest is the substitution s///: we substitute everything (.*) by the $varvariable
  • 1平均第一行
  • 剩下的就是替换s///:我们用$var变量替换所有内容 (.*)