So far I've been able to find how to add a line at the beginning of a file but that's not exactly what I want. I'll show it on a example
File content
some text at the beginning
Result
<added text> some text at the beginning
It's similar but I don't want to create any new line with it...
I would like to do this with sed
if possible.
Hi with carriage return:
sed
can operate on an address:What is this magical
1s
you see on every answer here? Line addressing!.Want to add
<added text>
on the first 10 lines?Or you can use
Command Grouping
:PROBLEM: tag a file, at the top of the file, with the base name of the parent directory.
I.e., for
tag the top of
file1
withProgramming
.SOLUTION 1 -- non-empty files:
1s
places the text at line 1 of the file.SOLUTION 2 -- empty or non-empty files:
The
sed
command, above, fails on empty files. Here is a solution, based on https://superuser.com/questions/246837/how-do-i-add-text-to-the-beginning-of-a-file-in-bash/246841#246841Note that the
-
in the cat command is required (reads standard input: seeman cat
for more information). Here, I believe, it's needed to take the output of the printf statement (to STDIN), and cat that and the file to temp ... See also the explanation at the bottom of http://www.linfo.org/cat.html.I also added
-f
to themv
command, to avoid being asked for confirmations when overwriting files.To recurse over a directory:
Note also that this will break over paths with spaces; there are solutions, elsewhere (e.g. file globbing, or
find . -type f ...
-type solutions) for those.ADDENDUM: Re: my last comment, this script will allow you to recurse over directories with spaces in the paths:
To insert just a newline:
Just for fun, here is a solution using
ed
which does not have the problem of not working on an empty file. You can put it into a shell script just like any other answer to this question.The above script adds the text to insert to the first line, and then joins the first and second line. To avoid ed exiting on error with an invalid join, it first creates a blank line at the end of the file and remove it later if it still exists.
Limitations: This script does not work if
<added text>
is exactly equal to a single period.You can use
cat -