Add comment if not present

I have a file

cat /root/file
#import node1
#import node2
import node2
import node4

After sed/awk operation the file should be as follows

cat /root/file
#import node1
#import node2
#import node2
#import node4

I was able to retrieve the #import, but not able to place comment in missing lines.

[root@server node]# cat /root/file  |  egrep  -o "[^ ]+import"
#import
#import

How about

sed 's/^[^#]/#&/' file
#import node1
#import node2
#import node2
#import node4

Providing a (verbose) awk variant...

awk '$0 !~ /^#/ { $0="#"$0 } { print }' file

Thanks rubic and junior-helper. How can we insert to file using awk, ie similar to sed -i

Hello anil510,

We can use following command for same.

sed -i 's/^[^#]/#&/'  Input_file

Thanks,
R. Singh

Unfortunately, awk has no such option. If you want to use the awk approach, you'll need something like

awk ... file > file.new
mv file.new file

PS: Under the hood, sed does the same :wink:

$ awk -F"#" ' NF==1 ? $0="#"$0 : 1 ' file
#import node1
#import node2
#import node2
#import node4
$ awk -F"#" ' $2 ? 1 : $0="#"$0 ' file
#import node1
#import node2
#import node2
#import node4
$ awk ' { sub("^[^#]","#&") } 1 ' file
#import node1
#import node2
#import node2
#import node4