我的数据类似于以下内容:
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
我正在寻找一种替换字段2中字符串的方法。如果数字不包含10-11个字符,我想将其替换为12223334444,这样输出将是:
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
我最初的想法是使用cut
获取第二个字段,然后使用grep "[1-9]"
或类似的字符来匹配9个或更少的字符。但是,我很确定有一种使用sed
或awk
的更有效的方法。任何指导将不胜感激。
答案 0 :(得分:4)
awk 'BEGIN{FS=OFS=","} $2<1000000000 || $2>99999999999 {$2=12223334444} {print}' file
或更短:
awk 'BEGIN{FS=OFS=","} $2<1000000000 || $2>99999999999 {$2=12223334444}1' file
或
awk 'BEGIN{FS=OFS=","} length($2)<10 || length($2)>11 {$2=12223334444}1' file
或
awk 'BEGIN{FS=OFS=","} {l=length($2)} l<10 || l>11 {$2=12223334444}1' file
或
awk -F, -v OFS=, '{l=length($2)} l<10 || l>11 {$2=12223334444}1' file
输出:
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
请参阅:8 Powerful Awk Built-in Variables – FS, OFS, RS, ORS, NR, NF, FILENAME, FNR
答案 1 :(得分:2)
另一个awk
$ awk 'BEGIN{FS=OFS=","} (s=length($2))!=10 && s!=11{$2=12223334444}1' file
或
$ awk 'BEGIN{FS=OFS=","} (s=length($2))<10 || s>11{$2=12223334444}1' file
可以打高尔夫球
$ awk 'BEGIN{FS=OFS=","} $2!~/^.{10,11}$/{$2=12223334444}1' file
答案 2 :(得分:1)
这可能对您有用(GNU sed):
sed -E '/^[^,]*,[^,]{10,11},/!s/[^,]*/12223334444/2' file
如果用,
分隔的第二个字段没有10或11个字符,请用12223334444
替换该字段。