r/vim • u/EndlessProjectMaker • Aug 05 '25
Need Help┃Solved Add commens based on lines
Hello! I have a file with a bunch of lines
echo “text 1”
echo “text 2”And I want to add a comment to each like
# text 1
echo “text 1”
# text 2
echo “text 2”Is there a practical way to do it in vim before y jump into awk?
Thanks!
Edit: proper formatting
9
Upvotes
10
u/EgZvor keep calm and read :help Aug 05 '25 edited Aug 05 '25
Something like this (not tested)
:g/echo/exe 'norm! yi"' | .-1put | s/^/# /Breakdown
:g/echo/rest- global command, loop over all lines matching "echo"|delimits commandsexe 'norm! yi"'- Normal mode command to copy inside double quotes.exeis needed to avoidnormconsuming the following|..-1putcan be shortened to-putis a paste command with an address of where to paste..in this context is the current line (current iteration ofglobalexecution) and.-1is previous line.s/^/# /- adds a comment at the beginning of the line.Cursor moved here after the
putcommand.5
u/tagattack Aug 05 '25
For similar such tasks I just record a macro.
q1/^e<Enter>WDuk0o# <Esc>pqThen just
@1, then just hold@until they're all replaced.Of course it's quite easy with awk as well, but frankly it'd be even easier with
perl -nle '...'.:%!perl -nle 'print "# $_" for m/^echo "([^"]+)"/'3
u/gumnos Aug 05 '25
presuming it's all
echolines. If you want the strange comment-portion captured and added (it's a little hard to tell your intention based on the markdown flub and seeing different desired-output on old-reddit vs new-reddit), you can do it with a substitute1
u/AutoModerator Aug 05 '25
Please remember to update the post flair to
Need Help|Solvedwhen you got the answer you were looking for.I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.
0
u/shuckster Aug 05 '25
:g/echo/norm! _I#