Rookie
Rookie

Reputation: 5477

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?

Upvotes: 96

Views: 110236

Answers (2)

Gilles Quénot
Gilles Quénot

Reputation: 185530

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
  • the double shell quotation is mandatory here

Learn how to quote properly in shell, it's very important :

"Double quote" every literal that contains spaces/metacharacters and every expansion: "$var", "$(command "$var")", "${array[@]}", "a & b". Use 'single quotes' for code or literal $'s: 'Costs $5 US', ssh host 'echo "$HOSTNAME"'. See
http://mywiki.wooledge.org/Quotes
http://mywiki.wooledge.org/Arguments
http://wiki.bash-hackers.org/syntax/words

Upvotes: 191

drvisor
drvisor

Reputation: 79

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

Upvotes: 6

Related Questions