change numerical value in file to characters via awk

Viewed 99

I'm looking to replace the numerical values in a file with a new value provided by me. Can be present in any part of the text, in some cases, it comes across as the third position but is not always necessarily the case. Also to try and save a new version of the file.

original format

A:fdg:user@server:r
A:g:1234:xtcy
A:d:1111:xtcy

modified format

A:fdg:user@server:rxtTncC
A:g:replaced_value:xtcy
A:d:replaced_value:xtcy

bash line command with awk:

awk -v newValue="newVALUE" 'BEGIN{FS=OFS=":"} /:.:.*:/ && ~/^[0-9]+$/{~=newValue} 1' original_file.txt > replaced_file.txt
4 Answers

You can simply use sed instead of awk:

sed -E 's/\b[0-9]+\b/replaced_value/g' /path/to/infile > /path/to/outfile

Here is an awk that asks you for replacement values for each numerical value it meets:

$ awk '
BEGIN {
    FS=OFS=":"                           # delimiters
}
{
    for(i=1;i<=NF;i++)                   # loop all fields
        if($i~/^[0-9]+$/) {              # if numerical value found
            printf "Provide replacement value for %d: ",$i > "/dev/stderr"
            getline $i < "/dev/stdin"    # ask for a replacement
        }
}1' file_in > file_out                   # write output to a new file

I would use GNU AWK for this task following way, let file.txt content be

A:fdg:user@server:rxtTncC
A:g:1234:xtcy
A:d:1111:xtcy

then

awk 'BEGIN{newvalue="replacement"}{gsub(/[[:digit:]]+/,newvalue);print}' file.txt

output

A:fdg:user@server:rxtTncC
A:g:replacement:xtcy
A:d:replacement:xtcy

Explanation: replace one or more digits using newvalue. Disclaimer: I assumed numeric is something consisting solely from digits.

(tested in gawk 4.2.1)

How about

awk -F : '$3 ~ /^[0-9]+$/ { $3 = "new value"} {print}' original_file >replaced_file

?

Related