Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to conditionally insert text via regex substitution in Vim?

Tags:

regex

vim

I have have several lines from a table that I’m converting from Excel to the Wiki format, and want to add link tags for part of the text on each line, if there is text in that field. I have started the converting job and come to this point:

|10.20.30.9||x|-||
|10.20.30.10||x|s04|Server 4|
|10.20.30.11||x|s05|Server 5|
|10.20.30.12|||||
|10.20.30.13|||||

What I want is to change the fourth column from, e.g., s04 to [[server:s04]]. I do not wish to add the link brackets if the line is empty, or if it contains -. If that - is a big problem, I can remove it.

All my tries on regex to get anything from the line ends in the whole line being replaced.

like image 707
user1410444 Avatar asked Dec 10 '22 00:12

user1410444


2 Answers

Consider using awk to do this:

#!/bin/bash

awk -F'|' '
{ 
  OFS = "|";
  if ($5 != "" && $5 != "-")
    $5 = "server:" $5;
  print $0
}'

NOTE: I've edited this script since the first version. This current one, IMO is better.

Then you can process it with:

cat $FILENAME | sh $AWK_SCRIPTNAME

The -F'|' switch tells awk to use | as a field separator. The if/else and printf statements are pretty self explanatory. It prints the fields, with 'server:' prepended to column 5, only if it is not "-" or "".

Why column 5 and not column 4?: Because you use | at the beginning of each record. So awk takes the 'first' field ($1) to be an empty string that it believes should have occured before this first |.

like image 171
ArjunShankar Avatar answered Feb 08 '23 22:02

ArjunShankar


This seems to do the job on the sample you give up there (with Vim):

%s/^|\%([^|]*|\)\{3}\zs[^|]*/\=(empty(submatch(0)) || submatch(0) == '-') ? submatch(0) : '[[server:'.submatch(0).']]'/
like image 36
Raimondi Avatar answered Feb 09 '23 00:02

Raimondi