Find the answer to your Linux question:
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 ...
Enjoy an ad free experience by logging in. Not a member yet? Register.
  1. #1
    Linux User
    Join Date
    Jul 2007
    Location
    Kronos
    Posts
    286

    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.

    Code:
     #!/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";
    Thank you

  2. #2
    tpl
    tpl is offline
    Linux User
    Join Date
    Jan 2007
    Location
    cleveland
    Posts
    476
    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 operate
    the sun is new every day (heraclitus)

  3. #3
    Linux User
    Join Date
    Jul 2007
    Location
    Kronos
    Posts
    286
    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.

  4. #4
    Linux 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

  5. #5
    Linux User
    Join Date
    Jul 2007
    Location
    Kronos
    Posts
    286
    Simple but clever!
    Thanks a lot for your help guys.

  6. #6
    Linux 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

  7. #7
    Linux User
    Join Date
    Aug 2006
    Posts
    458
    Quote Originally Posted by secondmouse View Post
    perl -i~ -0777pe's/^/New first line\n/' yourfile

    Reference: Insert line in the first line - Dev Archives
    cool, but for huge files, it will still be slower than using cat.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •