简体   繁体   中英

How add a square bracket to end of line in file using VIM

I have a text file with more than 500000 lines. I am using VIM to edit these files.

My text has set of square brackets in each line. Unfortunately, some of the lines don't have closing square brackets.

some text [ text

some text [ text]

some text [ text]

some text [ text

some text [ text]

I need my text to be

some text [text]

some text [text]

some text [text]

some text [text]

some text [text]

I'd like to know how to accomplish the result above using Vim.

:%s/[^\]]$/&]

substitutes every last character before EOL that is not a ] with itself followed by a ] , essentially adding a trailing bracket where there is none.

Now, in your initial snippet the opening bracket is separated by a space from the word that follows so you may need to run a second substitution to clean the whole thing up:

:%s/\[\s*/[

So many ways:

  • visual block - <cv> then select all the lines then press $A]<esc>
  • substitue - :%s/$/]/
  • via normal ex-command - :%normal A]
  • macros - qqA]jq then execute via 500000@q

Personally I would go with a the substitution.

@PeterRincker's solutions seem great to add a ] at the end of selected lines.

Here is a proposal to add a ] in one command to all non-empty lines of file not ending with ] (or with ] , followed by spaces):

:%s/[^\]]\+ *$/&]/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM