Skip to content
Advertisement

How To Replace Strings With X to Y Characters

I have data similar to the following:

2496,8805,1/7/19 18:58,9723308800
7,18538320322,1/7/19 19:22,13012881250
8827,9723308808,1/7/19 19:55,9723308800
3109,8801,1/7/19 19:56,19723308800

I am looking for a way to replace strings in field 2. If the number does not have 10-11 characters, I would like to replace it with 12223334444 so the output would be:

2496,12223334444,1/7/19 18:58,9723308800
7,18538320322,1/7/19 19:22,13012881250
8827,9723308808,1/7/19 19:55,9723308800
3109,12223334444,1/7/19 19:56,19723308800

My original thought was to use cut to get the second field and then use grep "[1-9]" or something similar to match 9 characters or less. However, I’m pretty sure there’s a more efficient way to do this using sed or awk. Any guidance would be highly appreciated.

Advertisement

Answer

awk 'BEGIN{FS=OFS=","} $2<1000000000 || $2>99999999999 {$2=12223334444} {print}' file

or shorter:

awk 'BEGIN{FS=OFS=","} $2<1000000000 || $2>99999999999 {$2=12223334444}1' file

or

awk 'BEGIN{FS=OFS=","} length($2)<10 || length($2)>11 {$2=12223334444}1' file

or

awk 'BEGIN{FS=OFS=","} {l=length($2)} l<10 || l>11 {$2=12223334444}1' file

or

awk -F, -v OFS=, '{l=length($2)} l<10 || l>11 {$2=12223334444}1' file

Output:

2496 12223334444 1/7/19 18:58 9723308800
7,18538320322,1/7/19 19:22,13012881250
8827,9723308808,1/7/19 19:55,9723308800
3109 12223334444 1/7/19 19:56 19723308800

See: 8 Powerful Awk Built-in Variables – FS, OFS, RS, ORS, NR, NF, FILENAME, FNR

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement