Note: Doing so may have unexpected side effects, notably replacing a symlink with a regular file, possibly ending up with different permissions on the file, and changing the file's creation (birth) date.
sed -i, as in Prince John Wesley's answer, tries to at least restore the original permissions, but the other limitations apply.
# create a file with content..
echo foo > /tmp/foo
# prepend a line containing "jim" to the file
sed -i "1s/^/jim\n/" /tmp/foo
# verify the content of the file has the new line prepened to it
cat /tmp/foo
This will work to form the output. The - means standard input, which is provide via the pipe from echo.
To rewrite the file a temporary file is required as cannot pipe back into the input file.
Prefer Adam's answer
We can make it easier to use sponge. Now we don't need to create a temporary file and rename it by
Another way using
sed
:If the line to be prepended is multiline:
If it's acceptable to replace the input file:
Note: Doing so may have unexpected side effects, notably replacing a symlink with a regular file, possibly ending up with different permissions on the file, and changing the file's creation (birth) date.
sed -i
, as in Prince John Wesley's answer, tries to at least restore the original permissions, but the other limitations apply.Note: Using a group command
{ ...; ... }
is more efficient than using a subshell ((...; ...)
).If the input file should be edited in place (preserving its inode with all its attributes):
Using the venerable
ed
POSIX utility:Note:
ed
invariably reads the input file as a whole into memory first.-s
suppresseded
's status messages.ed
as a multi-line here-document (<<'EOF' ... EOF
), i.e., via stdin.1i
makes1
(the 1st line) the current line and starts insert mode (i
)..
on its own line.w
writes the result back to the input file (for testing, replacew
with,p
to only print the result, without modifying the input file).-i
writes the change in place and take a backup if any extension is given. (In this case,.old
)1s;^;to be prepended;
substitutes the beginning of the first line by the given replacement string, using;
as a command delimiter.