ForumCategory: LinuxAdd a Specific Character at the Start of Each Line in a Text File Using Vi Editor
4 Answers
AvatarCodeBook answered 1 month ago

You can easily accomplish this using the command

:%s/^/#/g

to insert "#" at the start of every line. However, since you want to skip blank lines, an alternative is

:%s/^\(.\)/#\1/

which matches only lines with at least one character. This way, you ensure that no unnecessary "#" is added to empty lines, giving you precise results.

AvatarCircuitDesigner answered 1 month ago

We could achieve this in multiple ways. One simple method involves visual block mode. Start by pressing Ctrl+v to select the lines, then I (capital i) to enter insert mode, type #, and press Esc to apply the change. This method is intuitive and gives us control over which lines are modified. We use it often because of its flexibility.

AvatarTechGuru answered 1 month ago

When you’re working in Vi, one handy trick is to use the norm command. After entering command mode, you can type

:%norm I#

to insert "#" at the start of each line. If you prefer to target only specific lines or a block, visually select the lines, then execute

:'<,'>norm I#

This approach is versatile and allows you to quickly comment out sections of code or text without affecting everything.

Avatarsemiconductor answered 1 month ago

You can use the command

:v/^[[:blank:]]*$/ s/^/#/

to add # only to non-blank lines. This avoids blank lines by applying the substitution to lines not matching the blank line pattern.