vim - split line by comma and add prefix to each token

Slayer

I have lines like this:

<prefix> <token1>, <token2>, .... <tokenN>;

where the number of tokens is variable and each token is a character or digit.

I would like to split them up in Vim like this:

<prefix> <token1>;
<prefix> <token2>;
...
<prefix> <tokenN>;

I tried grabbing the pattern like this /<prefix>\s\+\(\w\+,\s*\)\{1,}\(\w\+\);/ but i'm not sure how to extract the variable number of tokens (\1 and \2 only given tokenN-1 and tokenN).

Thoughts? Thanks in advance.

filbranden

If your prefix is fixed everywhere (you suggested using a pattern starting with /<prefix>\s\+...), then you can probably use something as simple as:

:g/^<prefix>\s/s/,\s\+/;\r<prefix> /g

In other words, for every line starting with <prefix>, replace all commas (with following whitespace) with a semicolon, carriage return and the fixed <prefix> followed by a space.


But assuming your <prefix> is more complex and variable and you want to capture it in the regex:

One way to approach this with a :substitute command is to use a further call to a substitute() function as part of the replacement, which you can use to replace the arbitrary number of commas.

One possible approach is:

:s/\(\S\+\)\s\+[^,]*\zs\(,\s*[^,]*\)*\ze;$/\=substitute(submatch(0),',\s*',";\r".submatch(1)." ",'g')/

Breaking the pattern down:

  • \(\S\+\): Match the prefix in a capture group. (You can use something better, more specific than just non-blanks, to properly match only the lines you care about.)
  • \s\+: Skip whitespace.
  • [^,]*: Skip the first token.
  • \zs: Mark the start of the match. Substitution will only replace this part.
  • \(,\s*[^,]*\)*: Sequence of one or more tokens, preceded by a comma, and optional whitespace.
  • \ze: Mark the end of the match.
  • ;$: Match the semicolon at the end of it all.

At this point, the strategy is, again, to replace commas with semicolon, carriage return and prefix, but doing so dynamically.

That's achieved by using these in the replacement:

  • \=: Use an expression in the replacement (see :help sub-replace-expression.)
  • substitute(submatch(0),',\s*',";\r".submatch(1)." ",'g'): Replace commas (and optional whitespace following them) with a sequence of semicolon, carriage return and prefix, followed by a space.
  • submatch(0): We're performing such replacement on the match (part in between the \zs and \ze only.)
  • ";\r": Beginning of the replacement, the semicolon and carriage return.
  • .: The dot operator concatenates strings in Vimscript.
  • submatch(1): Refers back to capture group 1, which we used in this case to capture the prefix.
  • 'g': Replace all matches.

This is a fairly complex replacement, but has the advantage of taking care of the substitution in a single :s command, which makes it easier to use it in a range or to later repeat it without having to record a macro.

The technique of using the substitute() function in a :s replacement is also an useful one to handle cases where capture groups are not enough, such as the one you present.

이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.

침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제

에서 수정
0

몇 마디 만하겠습니다

0리뷰
로그인참여 후 검토

관련 기사

분류에서Dev

add / at the end of each line

분류에서Dev

Add prefix and suffix to every line in a .txt file

분류에서Dev

Powershell - Prefix each line of Format-Table with String

분류에서Dev

How to Remove last comma of each line on csv using linux

분류에서Dev

How to Remove last comma of each line on csv using linux

분류에서Dev

Vim: Replace first word on each line of selection with number in list

분류에서Dev

Add a line below each line matching a pattern only if not already present

분류에서Dev

Add and number blank line above each line in a file

분류에서Dev

remove characters from a list and add a line break from each element

분류에서Dev

Add text to beginning and end of each line using batch/cmd

분류에서Dev

sas add prefix to column names

분류에서Dev

xslt - for each - line-by-line

분류에서Dev

Pandas : add a prefix to data following a certain position

분류에서Dev

Add zero prefix of the number in Perl for date conversion

분류에서Dev

Copy filenames, and add path prefix, in a directory, recursively

분류에서Dev

Split text in cells at line breaks

분류에서Dev

Split comma delimited string and select top "SearchTags" ordered by count

분류에서Dev

MVC add token in http header

분류에서Dev

how to manually add csrf token

분류에서Dev

GORM: automatically prefix each table name with the domain class namespace

분류에서Dev

convert int number to separated number each 3 digits by comma

분류에서Dev

How to combine each subarray of subarrays and store them as comma separated strings?

분류에서Dev

Bash - pair each line of file

분류에서Dev

Vim: automate reading line from external file

분류에서Dev

Vim : How to actually insert line numbers in the file?

분류에서Dev

vim: find a line containing pattern that is not in the neighbouring lines

분류에서Dev

Comma, colon, decorator or end of line expected after operand

분류에서Dev

vim, how to search text and prepend new line before searched line

분류에서Dev

Split line by +-*/() (as delimeters) without omitting them in python

Related 관련 기사

  1. 1

    add / at the end of each line

  2. 2

    Add prefix and suffix to every line in a .txt file

  3. 3

    Powershell - Prefix each line of Format-Table with String

  4. 4

    How to Remove last comma of each line on csv using linux

  5. 5

    How to Remove last comma of each line on csv using linux

  6. 6

    Vim: Replace first word on each line of selection with number in list

  7. 7

    Add a line below each line matching a pattern only if not already present

  8. 8

    Add and number blank line above each line in a file

  9. 9

    remove characters from a list and add a line break from each element

  10. 10

    Add text to beginning and end of each line using batch/cmd

  11. 11

    sas add prefix to column names

  12. 12

    xslt - for each - line-by-line

  13. 13

    Pandas : add a prefix to data following a certain position

  14. 14

    Add zero prefix of the number in Perl for date conversion

  15. 15

    Copy filenames, and add path prefix, in a directory, recursively

  16. 16

    Split text in cells at line breaks

  17. 17

    Split comma delimited string and select top "SearchTags" ordered by count

  18. 18

    MVC add token in http header

  19. 19

    how to manually add csrf token

  20. 20

    GORM: automatically prefix each table name with the domain class namespace

  21. 21

    convert int number to separated number each 3 digits by comma

  22. 22

    How to combine each subarray of subarrays and store them as comma separated strings?

  23. 23

    Bash - pair each line of file

  24. 24

    Vim: automate reading line from external file

  25. 25

    Vim : How to actually insert line numbers in the file?

  26. 26

    vim: find a line containing pattern that is not in the neighbouring lines

  27. 27

    Comma, colon, decorator or end of line expected after operand

  28. 28

    vim, how to search text and prepend new line before searched line

  29. 29

    Split line by +-*/() (as delimeters) without omitting them in python

뜨겁다태그

보관