Increment numbers greater than 50 in a file

  • Increment all numbers with absolute value greater than 50.

    perl -pe 's/\b(\d+)\b/$1>50 ? $1+1 : $1/ge' file
    

    The pattern is a sequence of digits (\d+) with boundaries (\b), so that it does not match the number 4 in set4ByteField, for example. The e flag at the end of the command allows the replacement to be treated as an expression, which is namely a ternary expresion on the captured group.

  • Increment all numbers greater than 50.

    perl -pe 's/(^|[^-])\b(\d+)\b/$1.($2>50 ? $2+1 : $2)/ge' file
    

    ^|[^-] matches the start of line or any character other than hyphen-minus to the left of the digits sequence. This rules out negative numbers.

By the way, you should not write to a file and read from it at the same time. Your attempt truncates the file before ever processing it, so you get an empty file. To edit the file in place, use Perl's -i flag (see the command-line options). Better still, -i.bak saves the original file with a .bak extension in case something goes wrong.


Your awk was almost right, but you want to alternate a field and then print the whole line. Also the output field separator is just removed and the missing comma and closing parentheses added manually:

awk 'BEGIN {FS="[,)]" ; OFS="" } /ByteField/ && $2 > 50 {$2=", "$2+1")"} ; 1' file

Where the 1 is always true, so always prints the line (for all lines) - note that it must be done after you altered the field. I added a match for /ByteField/ for more robustness.

For replacing the file: The redundant cat and piping to a command that has the same file as output will break. Use other approaches. E.g.

With GNU awk

awk -i inplace 'BEGIN ....' file

With sponge

awk 'BEGIN ...' file | sponge file

Or with help of a temporary file

awk 'BEGIN ...' file > file.alt
mv file.alt file

Tags:

Perl

Awk

Sed