Monday, April 25, 2011

How can I add * to the end of each line in Vim?

I tried the code unsuccessfully

:%s/\n/*\n/g
From stackoverflow
  • :%s/$/\*/g

    should work. So should :%s/$/*/g as MrWiggles points out correctly.

    MrWiggles : +1. No need to escape the asterisk in the replacement tho
    dirkgently : Yup. More readable to me with one, though.
    MrWiggles : I won't argue, you have an awesome username so that gets you kudos points ;-)
    Aman Jain : Is there a way to insert '*' at the same column, since all lines are not of same length, so line 1 might have '*' at 15th column, but line 2 has '*' at 25th column.
  • %s/\s*$/*/g

    this will do the trick, and ensure leading spaces are ignored.

  • :%s/\n/*\r/g

    Your first one is correct anywhere else, but Vim has to have different newline handling for some reason.

    Nathan Fellman : In my version of Vim \n works, but this just replaces the newline with a *, effectively joining the lines.
    Ant P. : This command is verified to work fine on every version of Vim I've tried. Are you using the windows version or something?
  • Note there is no need for the trailing 'g' as only one replacement is possible.

    : "as only one replacement is possible" *per line*
    Masi : Thank you Neil! Simplicity is always beautiful :)
  • Another option no-one has mentioned is

    :g/$/s//*

    Masi : What does s// mean in the regex? I know a similar command, :g/ / /p, (grep). I am pretty sure that your command is close to mine, at least in the structure.
    paxdiablo : The s is substitute - it replace the end of line anchor with the asterisk (well, not actually replaces it since it's an anchor point).
  • Also:

    :g/$/norm A*
    

    Also:

    gg<Ctrl-v>G$A*<Esc>
    
  • Even shorter than the :search command:

    :%norm A*
    

    This is what it means:

     %       = for every line
     norm    = type the following commands
     A*      = append '*' to the end of current line
    
    smcameron : Man, there exists no vi or vim thread from which I do not learn something. Today I learn about norm. And as they say at Cheers, "Norm!"
    Nathan Fellman : Ditto - voted up for "norm"

0 comments:

Post a Comment