Results 1 to 7 of 7
Hello
Can anyone tell me how I can insert a text in the first line of a file. I'm trying to do that with the following, but it writes the ...
- 05-28-2009 #1Linux User
- Join Date
- Jul 2007
- Location
- Greece
- Posts
- 277
insert text in the first line of a file
Hello
Can anyone tell me how I can insert a text in the first line of a file. I'm trying to do that with the following, but it writes the file at the end of it.
Thank youCode:#!/usr/bin/perl use strict; system ("touch /tmp/txtfile"); my ($fileappend, $fileread, $filein); $filein = '/tmp/txtfile'; open $fileread, '>', $filein || die ("Can't open: $filein $!"); print $fileread "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n"; # Creates 20 blank lines close $fileread; open ($fileappend, ">>$filein"); # Open for appending print $fileappend "blabla";
- 05-28-2009 #2Linux User
- Join Date
- Jan 2007
- Location
- cleveland
- Posts
- 452
let's suppose you have a line "abcdefg" first in file N
and you want it to read "abctestdefg" inserting "test"
between "c" and "d"
sed 's1/cd/ctestd/' <N
where the "1" is the lline number on which to operatethe sun is new every day (heraclitus)
- 05-28-2009 #3Linux User
- Join Date
- Jul 2007
- Location
- Greece
- Posts
- 277
Thank you for replying tpl
But what if the line is blank, and want to write ctestd only.
I tried this
sed 's1//ctestd/' <N but didn't work.
- 05-28-2009 #4Linux User
- Join Date
- Aug 2006
- Posts
- 458
very simply , you could just use cat
Code:# echo "text to insert" >> temp # cat file >> temp # mv temp file
- 05-28-2009 #5Linux User
- Join Date
- Jul 2007
- Location
- Greece
- Posts
- 277
Simple but clever!
Thanks a lot for your help guys.
- 05-29-2009 #6Linux User
- Join Date
- May 2008
- Location
- NYC, moved from KS & MO
- Posts
- 251
perl -i~ -0777pe's/^/New first line\n/' yourfile
Reference: Insert line in the first line - Dev Archives
- 05-29-2009 #7Linux User
- Join Date
- Aug 2006
- Posts
- 458


Reply With Quote
