Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace the first line in a text file by a string

Tags:

linux

shell

unix

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?

like image 633
Rookie Avatar asked Nov 18 '12 06:11

Rookie


People also ask

How do I change the first line of a file in Java?

Invoke the replaceAll() method on the obtained string passing the line to be replaced (old line) and replacement line (new line) as parameters. Instantiate the FileWriter class. Add the results of the replaceAll() method the FileWriter object using the append() method.

How do I replace a string in a text file?

To replace text in a file we are going to open the file in read-only using the open() function. Then we will t=read and replace the content in the text file using the read() and replace() functions.


2 Answers

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
like image 66
Gilles Quenot Avatar answered Oct 02 '22 12:10

Gilles Quenot


You can do this easy with tail:

#I want to replace the first line cp test.txt test.txt.backup echo 'mynewfirstline'> test.txt #add everything from old file starting from second line cat test.txt.backup |tail -n+2>> test.txt 
like image 40
drvisor Avatar answered Oct 02 '22 11:10

drvisor