用字符串替换文本文件中的第一行

时间:2022-06-02 19:22:48

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)

我想用movie替换第一行(movie file path)。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吗?

1 个解决方案

#1


81  

sed is the right tool, try doing :

sed是正确的工具,请尝试:

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

explanations

解释

  • 1 mean first line
  • 1的意思是第一行
  • the rest is the substitution s/// : we substitute everything (.*) by the $var variable
  • 其余部分是替换s//:我们用$var变量替换所有(.*)

#1


81  

sed is the right tool, try doing :

sed是正确的工具,请尝试:

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

explanations

解释

  • 1 mean first line
  • 1的意思是第一行
  • the rest is the substitution s/// : we substitute everything (.*) by the $var variable
  • 其余部分是替换s//:我们用$var变量替换所有(.*)