Find the answer to your Linux question:
Results 1 to 4 of 4
I have a log file which I send a line of text to. I use the "echo sometext >> logfile" at the moment. When I add a line to this ...
  1. #1
    Just Joined!
    Join Date
    Aug 2006
    Posts
    8

    Inserting lines at the start of a text file

    I have a log file which I send a line of text to. I use the "echo sometext >> logfile" at the moment.

    When I add a line to this text file I want to insert it and the new line to become the first line in the file not the last...Any thoughts Or can someone help with a bash script snippet that reads the contents of my file and writes it to a new file in reverse order ? Theres probably only ~100 lines of text in the file

    Cheers

    rob
    Australia

  2. #2
    drl
    drl is offline
    Linux Engineer drl's Avatar
    Join Date
    Apr 2006
    Location
    Saint Paul, MN, USA / CentOS, Debian, Solaris, SuSE
    Posts
    1,117
    Hi.

    In Linux, I see:
    Code:
    % man -k reverse
    rev (1)              - reverse lines of a file
    tac (1)              - concatenate and print files in reverse
    Perhaps you can build upon these ... cheers, drl
    Welcome - get the most out of the forum by reading forum basics and guidelines: click here.
    90% of questions can be answered by using man pages, Quick Search, Advanced Search, Google search, Wikipedia.
    We look forward to helping you with the challenge of the other 10%.
    ( Mn, 2.6.n, AMD-64 3000+, ASUS A8V Deluxe, 1 GB, SATA + IDE, Matrox G400 AGP )

  3. #3
    Just Joined!
    Join Date
    Aug 2007
    Posts
    37
    As drl says, you could use tac:
    Code:
    LOGFILE=/path/to/logfile
    TEMP=/tmp/templogfile
    
    tac $LOGFILE >$TEMP
    echo "This is line One" >>$TEMP
    tac $TEMP >$LOGFILE
    Or you could do it this way:
    Code:
    LOGFILE=/path/to/logfile
    TEMP=/tmp/templogfile
    
    echo "This is line Uno" >$TEMP
    cat $LOGFILE >>$TEMP
    mv $TEMP $LOGFILE

  4. #4
    Linux User
    Join Date
    Aug 2006
    Posts
    458
    Quote Originally Posted by Bad Inferno View Post
    I have a log file which I send a line of text to. I use the "echo sometext >> logfile" at the moment.

    When I add a line to this text file I want to insert it and the new line to become the first line in the file not the last...Any thoughts Or can someone help with a bash script snippet that reads the contents of my file and writes it to a new file in reverse order ? Theres probably only ~100 lines of text in the file

    Cheers

    rob
    Australia
    1)
    Code:
    echo "sometext" > sometext.txt
    cat sometext.txt logfile > putfile
    2)
    Code:
    sed -i '1i sometext' logfile

Posting Permissions

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