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:





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


ADD Text to the End of file

for File in `find . -iname "*.php"`
echo "Append your stuff here" >> $File

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