awk agrega un valor al campo

awk agrega un valor al campo

Estoy buscando una idea sobre cómo agregar un valor a un campo. Mi archivo se ve así:

line(001)=YR200PR1030,YR230PR1580,YR340PR2016,
          YR450PR2450,
          PRF3500,
line(002)=YR200PR452,YR230PR740,YR340PR1500,
          YR450PR2120,
          PRF2800,

y quiero agregar un valor de 32 a cada valor entre YR y PR, por ejemplo:
YR200PR1030-->YR232PR1030

¿alguna idea? gracias.

Respuesta1

Si lo que necesitas es incrementar el valor numérico encontrado entre cada aparición de YRy PR, puedes intentar:

$ perl -pe 's/YR(\d+)PR/sprintf("YR%sPR",$1 + 32)/eg' file
line(001)=YR232PR1030,YR262PR1580,YR372PR2016,
          YR482PR2450,
          PRF3500,
line(002)=YR232PR452,YR262PR740,YR372PR1500,
          YR482PR2120,
          PRF2800,

O bien, para editar el archivo en su lugar:

perl -i -pe 's/YR(\d+)PR/sprintf("YR%sPR",$1 + 32)/eg' file

Los -pesignificados "pagimprime cada línea después de aplicar el script dado por -e". El script en sí es solo un operador de sustitución ( s/old/new/) con la /gbandera para "global" (coincide con cada aparición en la línea) y /eque nos permite ejecutar código en la mano derecha. lado del operador Finalmente, la expresión regular hará coincidir uno o más dígitos ( \d+) entre a YRy a PR, capturando los dígitos como $1, y luego el reemplazo imprimirá YR, el número capturado más 32 y PR.

Respuesta2

Usando cualquier awk en cualquier shell en cada caja UNIX:

$ cat tst.awk
{
    while ( match($0,/YR[0-9]+PR/) ) {
        printf "%s%d", substr($0,1,RSTART+1), substr($0,RSTART+2)+32
        $0 = substr($0,RSTART+RLENGTH-2)
    }
    print
}

.

$ awk -f tst.awk file
line(001)=YR232PR1030,YR262PR1580,YR372PR2016,
          YR482PR2450,
          PRF3500,
line(002)=YR232PR452,YR262PR740,YR372PR1500,
          YR482PR2120,
          PRF2800,

Respuesta3

Dominio

for ((j=1;j<=2;j++)); do awk -v j="$j" -F "," 'NR==j && ORS=","{for(i=1;i<=NF;i++){if ($i ~ /^YR[0-9]*PR[0-9]*/){print substr($i,1,2)substr($i,3,3)+32substr($i,6)}else {print $i}}}' p.txt; echo -e "\n"; done

producción

YR232PR1030,YR262PR1580,YR372PR2016,YR482PR2450,

YR232PR452,YR262PR740,YR372PR1500,YR482PR2120,PRF2800,

información relacionada