Tuesday, May 18, 2010

How To Add a Line into the middle of a Text File

SkyHi @ Tuesday, May 18, 2010

Here is a quick tip on how to use sed to add a line into the middle of a text file from the command line, without opening it.


To clarify, let’s say you have a text file that has four lines:



Line1Text

Line2Text

Line3Text

Line4Text


Using sed, you can append a line anywhere you want with a simple command without even knowing the line numbers.


Add a Line into the Middle of a Text File


For this example, lets say we want to append a new line under Line3Text:



# sed '/^Line3Text/a NewLineText' textFile > newFile


You’ll notice that we output the results to a newFile so that we can make sure the new line appended correctly before overwriting the original file. If you check the newFile, you should see a correct output, then you can overwrite the original textFile.



# mv newFile textFile

REFERENCES
http://www.foogazi.com/2008/06/24/quickzi-how-to-add-a-line-into-the-middle-of-a-text-file/



ADD Text to the End of file

#!/bin/bash
for File in `find . -iname "*.php"`
do
echo "Append your stuff here" >> $File
done


If -e is in effect, the following sequences are recognized:

\0NNN the character whose ASCII code is NNN (octal)

\\ backslash

\a alert (BEL)

\b backspace

\c suppress trailing newline

\f form feed

\n new line

\r carriage return

\t horizontal tab

\v vertical tab


REFERENCES
http://forums.fedoraforum.org/showthread.php?t=225470