Как найти расположение символов строки в файле?

Con KVM tiene la opción de hacer instantáneas internas y externas. Hasta ahora, el administrador virt -solo admite instantáneas internas. Si necesita instantáneas externas, debe usar herramientas de línea de comandos. Un script de shell muy útil es this . Lo he usado durante años,con solo dos entradas crontab necesarias:

10 0***/usr/local/bin/fi -backup.sh -q -v todos > /dev/null

0 23**sol /usr/local/bin/fi -backup.sh -c -v todos > /dev/null

La primera entrada crea instantáneas de todas las máquinas virtuales en ejecución. La segunda entrada consolida todas las instantáneas en la imagen una vez por semana.

Necesita secuencias de comandos adicionales para copiar las instantáneas en su ubicación de copia de seguridad, y para limpiar automáticamente las instantáneas antiguas de esa ubicación de copia de seguridad.

4
22.07.2019, 12:26
3 ответа

В текущих версиях Perl вы можете использовать магические массивы @-и @+для получения позиций совпадений всего регулярного выражения и любых возможных групп захвата. Нулевой элемент обоих массивов содержит индексы, относящиеся ко всей подстроке, поэтому вас интересует $-[0].

В виде одного -вкладыша:

$ echo 'aöæaæaæa' | perl -CSDLA -ne 'BEGIN { $pattern = shift }; printf "%d\n", $-[0] while $_ =~ m/$pattern/g;'  æa
2
4
6

Или полный скрипт:

#!/usr/bin/perl

use strict;
use warnings;
use utf8;
use Encode;
use open  ":encoding(utf8)";
undef $/;
my $pattern = decode_utf8(shift);
binmode STDIN, ":utf8";
while (<STDIN>) {
    printf "%d\n", $-[0] while $_ =~ m/$pattern/g;
}

напр.

$ echo 'aöæaæaæa' | perl match.pl æa -
2
4
6

(Последний сценарий работает только для стандартного ввода. Кажется, мне трудно заставить Perl обрабатывать все файлы как UTF -8.)

2
27.01.2020, 20:51

Сzsh:

set -o extendedglob # for (#m) which in patterns causes the matched portion to be
                    # made available in $MATCH and the offset (1-based) in $MBEGIN
                    # (and causes the expansion of the replacement in
                    # ${var//pattern/replacement} to be deferred to the
                    # time of replacement)

haystack=aöæaæaæa
needle=æ

offsets=() i=0
: ${haystack//(#m)$needle/$((offsets[++i] = MBEGIN - 1))}
print -l $offsets
2
27.01.2020, 20:51

С GNU awkили любой другой совместимой с POSIX awkреализацией (неmawk)и правильным набором локали:

$ LANG='en_US.UTF-8' gawk -v pat='æa' -- '
{
    s = $0;
    pos = 0;
    while (match(s, pat)) {
        pos += RSTART-1;
        print "file", FILENAME ": line", FNR, "position", pos, "matched", substr(s, RSTART, RLENGTH);
        pos += RLENGTH;
        s = substr(s, RSTART+RLENGTH);
    }
}
' <<<'aöæaæaæa'
file -: line 1 position 2 matched æa
file -: line 1 position 4 matched æa
file -: line 1 position 6 matched æa
$

Шаблон, указанный в аргументе -v patдля gawk, может быть любым допустимым регулярным выражением.

2
27.01.2020, 20:51

Теги

Похожие вопросы