Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
498 views
in Technique[技术] by (71.8m points)

linux - Replace the first line in a text file by a string

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:

/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)

Please guide me how to do this. I came across sed in some posts, do I need to use sed here?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

sed is the right tool, try doing :

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...