Insert line based on found string

Hi All
I'm trying to insert a new line at the before each comment line in a file.
Comment lines start with '#-----'
there are other comments with in lines but I don't want a new line there.
Example file:

blah
blah #do not insert here
#this is a comment
blah #some more 
#another comment

the desired result would be

blah
blah #do not insert here

#this is a comment
blah #some more 

#another comment

I tried

tr '#' '\012' 

and a number of variants using sed etc but I don't get the desired result.

grateful for any pointers . . .

Hello Mudshark,

Could you please try following and let me know if this helps you.

awk '/^#/{print RS $0;next} 1'   Input_file

Output will be as follows.

blah
blah #do not insert here

#this is a comment
blah #some more 

#another comment

Thanks,
R. Singh

1 Like

And in sed :

 sed '/^#/{x;p;x;}' input-file
2 Likes

Many thanks all for the responses.
RavinderSingh13 - That worked ok although I had to use nawk on Solaris.
greet_sed - that also worked fine.
I also found another similar thread and used this ... ( where filename = 'x' and comment lines start with '#-')

nawk '{ gsub ("#-", "\n#-") }1' x

Try also

sed 's/^#/\n#/' file
1 Like

Unix sed needs backslash-realnewline i.e. needs multi-line

sed 's/^#/\
#/' file

Or insert an empty line with

sed '/^#/i\
' file
awk '/^#/{print x}1' file

Hi greet_sed,
Could you please explain how below part is working.

{x;p;x;}

---------- Post updated at 01:01 PM ---------- Previous update was at 12:55 PM ----------

Hi Scrutinizer,
How print x is printing a new line , and when i keep blank like below

awk '/^#/{print }1' file

it prints comment line twice. Please explain.

Hello looney,

So when you do print x it will print actually a NULL value(which is in other words will be a new line only because there is NO value for vriable named x here). But when we do print , it will definetly print line starting with # 2 times because you have given command print without mentioning any line eg--> $0 or any variable like print x so by default it will print the current line(which offcourse is the line which is starting from # ), then it will print it again because we have mentioned 1 there.
So awk works on method of condition{action} and by writing 1 here we are making the condition part as TRUE so action should occure here but we haven't mentioned any action to be done so by default action which is print will print the current line(which is again line starting with # ), so that is why print x prints a new line(value of variable x which is NULL and then line's value which starts with # ) and print} 1 part prints line 2 times because both of the times we are giving instructions to awk to print the line starting with # as explained above.

Thanks,
R. Singh

1 Like

Hi,

Hope it helps.

And just for the ex of it try the script below whose only pros is that the file is modified in place...

ex -s file <<eof
g/^#/i|
.
x
eof