Notepad++ reemplazar gradualmente


Digamos que quiero tener 10 filas de datos pero quiero un valor para incrementar para cada fila o pieza de datos. ¿Cómo puedo incrementar ese valor?

Por ejemplo....Si tengo estas filas, ¿hay una forma regex de reemplazar los valores id para incrementar?

<row id="1" />
<row id="1" />
<row id="1" />
<row id="1" />
<row id="1" />

- - - Esto es lo que me gustaría que se vea... (si el id de la primera fila sube, eso está bien)

<row id="1" />
<row id="2" />
<row id="3" />
<row id="4" />
<row id="5" />
Author: dreftymac, 2011-09-30

8 answers

No estoy seguro acerca de regex, pero hay una manera de hacer esto en Notepad++, aunque no es muy flexible.

En el ejemplo que dio, mantenga pulsado Alt y seleccione la columna de números que desea cambiar. Luego vaya a Edit->Column Editor y seleccione el botón de opción Number to Insert en la ventana que aparece. A continuación, especifique su número inicial y el incremento, y pulse Aceptar. Debe escribir los números incrementados.

Nota: esto también funciona con la función Multi-editing (seleccionar varias ubicaciones manteniendo pulsada la tecla Ctrl ).

Esto, sin embargo, no se acerca a la flexibilidad que la mayoría de la gente encontraría útil. Notepad++ es genial, pero si quieres un editor realmente poderoso que pueda hacer cosas como esta con facilidad, diría que use Vim.

 143
Author: voithos,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-08-01 06:32:51

Estaba buscando la misma característica hoy, pero no pude hacer esto en Notepad++. Sin embargo, tenemos TextPad a nuestro rescate. Funcionó para mí.

En el cuadro de diálogo reemplazar de TextPad, active regex; luego podría intentar reemplazar

<row id="1"/>

Por

<row id="\i"/>

Eche un vistazo a este enlace para obtener más increíbles funciones de reemplazo de TextPad - http://sublimetext.userecho.com/topic/106519-generate-a-sequence-of-numbers-increment-replace/

 13
Author: Bipin Mangwani,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-02-04 09:22:48

Dado que hay respuestas reales limitadas, compartiré esta solución. Para realmente casos simples como tu ejemplo lo haces al revés...

De esto

1
2
3
4
5

Reemplace \r\n con " />\r\n<row id=" y obtendrá el 90% del camino

1" />
<row id="2" />
<row id="3" />
<row id="4" />
<row id="5

O es una manera similar se puede hackear sobre los datos con excel/hoja de cálculo. Simplemente divida sus datos originales en columnas y manipule los valores según lo requiera.

|   <row id="   |   1   |   " />    |
|   <row id="   |   1   |   " />    |
|   <row id="   |   1   |   " />    |
|   <row id="   |   1   |   " />    |
|   <row id="   |   1   |   " />    |

Cosas obvias, pero puede ayudar a alguien a hacer el extraño trabajo hack para guardar algunos golpes de tecla.

 5
Author: KCD,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-07-12 03:40:54


Las soluciones sugeridas anteriormente solo funcionarán si los datos están alineados..
Ver solución en el enlace usando PythonScript Notepad++ plugin, Funciona muy bien!

Stackoverflow Buscar / Reemplazar pero Incrementar Valor

 3
Author: user648026,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 12:10:30

Tuve el mismo problema con más de 250 líneas y así es como lo hice:

Por ejemplo:

<row id="1" />
<row id="1" />
<row id="1" />
<row id="1" />
<row id="1" />

Pones el cursor justo después del " 1 " y haces clic en alt + shift y empiezas a descender con la flecha hacia abajo hasta que llegues a la línea inferior ahora ves un grupo de selecciones haz clic en borrar para borrar el número 1 en cada línea simultáneamente y ve a Edit -> Column Editor y selecciona Number to Insert luego coloca 1 en el campo de número inicial y 1 en incrementado por campo y comprueba ok

Felicitaciones por haberlo hecho :)

 3
Author: Mourad El Aomari,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-03-25 12:43:32

Http://docs.notepad-plus-plus.org/index.php/Inserting_Variable_Text

Notepad++ viene equipado con un Editor Edit -> Column "Alt+C" que puede trabajar en una selección rectangular de dos maneras diferentes: Coledit.png insertar algún texto fijo en cada línea incluyendo y siguiendo la línea actual, en la columna del punto de inserción (también conocido como caret). El texto seleccionado inicialmente se deja intacto. Como ilustra la imagen, se puede insertar una serie lineal de números en el mismo manera. Se debe proporcionar el valor inicial y el incremento. El relleno izquierdo con ceros es una opción, y el número se puede introducir en base 2, 8, 10 o 16 - así es como se mostrarán los valores calculados también, el relleno se basa en el más grande.

 3
Author: Ailson Costa,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-04-13 19:05:50

(Publicación en caso de que alguien pueda tener un uso de ella).

Estaba buscando una solución para un problema un poco más sofisticado que OP-reemplazar CADA ocurrencia de algo con el número por la misma cosa con número incrementado

Por ejemplo, Reemplazar algo como esto:

<row id="1" />
<row id="2" />
<row id="1" />
<row id="3" />
<row id="1" />

Por esto:

<row id="2" />
<row id="3" />
<row id="2" />
<row id="4" />
<row id="2" />

No pude encontrar la solución en línea, así que escribí mi propio script en groovy (un poco feo, pero hace el trabajo):

 /**
 * <p> Finds words that matches template and increases them by 1.
 * '_' in word template represents number.
 *
 * <p> E.g. if template equals 'Row="_"', then:
 * ALL Row=0 will be replaced by Row="1"
 * All Row=1 will be replaced by Row="2"
 * <p> Warning - your find template might not work properly if _ is the last character of it
 * etc.
 * <p> Requirments:
 * - Original text does not contain tepmlate string
 * - Only numbers in non-disrupted sequence are incremented and replaced
 * (i.e. from example below, if Row=4 exists in original text, but Row=3 not, than Row=4 will NOT be 
 * replaced by Row=5)
 */
def replace_inc(String text, int startingIndex, String findTemplate) {
    assert findTemplate.contains('_') : 'search template needs to contain "_" placeholder'
    assert !(findTemplate.replaceFirst('_','').contains('_')) : 'only one "_" placeholder is allowed'
    assert !text.contains('_____') : 'input text should not contain "______" (5 underscores)'
    while (true) {
        findString = findTemplate.replace("_",(startingIndex).toString())
        if (!text.contains(findString)) break;
        replaceString = findTemplate.replace("_", "_____"+(++startingIndex).toString())
        text = text.replaceAll(findString, replaceString)
    }
    return text.replaceAll("_____","") // get rid of '_____' character
}

// input
findTemplate = 'Row="_"'
path = /C:\TEMP\working_copy.txt/
startingIndex = 0

// do stuff
f = new File(path)
outText = replace_inc(f.text,startingIndex,findTemplate)
println "Results \n: " + outText
f.withWriter { out -> out.println outText }
println "Results written to $f"
 2
Author: Kranach,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-05-19 09:15:01

Puede hacerlo utilizando Powershell a través de regex y bucle foreach, si almacena sus valores en la entrada file .txt :

$initialNum=1; $increment=1; $tmp = Get-Content input.txt | foreach {  $n = [regex]::match($_,'id="(\d+)"').groups[1
].value; if ($n) {$_ -replace "$n", ([int32]$initialNum+$increment); $increment=$increment+1;} else {$_}; }

Después de eso puede almacenar $tmp en el archivo usando $tmp > result.txt. Esto no necesita que los datos estén en columnas.

 1
Author: Ivan G,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-11-14 22:14:51