搜索多个精确模式以替换为sed或awk

时间:2018-02-08 12:39:14

标签: bash awk sed

我的主机名之后有多个域名。

abc-ddddd-guru.prod.gama1.com
ddf-yy1.gama1.com
ccd-dlf89-01.cdfgama1.com
kk1-dlf88.gg1-gama1.com
radaas.gama1.com

当我尝试使用sed在每个域名之前添加ilo时...它没有完全发生

#sed 's/gama1.com/-ilo.gama1.com/g; s/cdfgama1.com/-ilo.cdfgama1.com/g' ; s/gg1-gama1.com/-ilo.gg1-gama1.com/g' ; s/prod.gama1.com/-ilo.prod.gama1.com/g'

OP:

abc-ddddd-guru.prod.-ilo.gama1.com
    ddf-yy1.-ilo.gama1.com
    ccd-dlf89-01.cdf-ilo.gama1.com
    kk1-dlf88.gg1--ilo.gama1.com
    radaas.-ilo.gama1.com

请帮助..谢谢

5 个答案:

答案 0 :(得分:2)

sed 解决方案:

sed -E 's/([^.]*|prod\.)?gama1.com$/-ilo.&/' file
  • ([^.]*|prod\.)? - 正则表达式替换组,匹配除.(由[^.]*提供)或prod.子域名之外的任何字符。
     ?量词告诉在0到1次之间匹配上述组

  • & - sed 的替换值,指向整场比赛

输出:

abc-ddddd-guru.-ilo.prod.gama1.com
ddf-yy1.-ilo.gama1.com
ccd-dlf89-01.-ilo.cdfgama1.com
kk1-dlf88.-ilo.gg1-gama1.com
radaas.-ilo.gama1.com

答案 1 :(得分:2)

关注awk可能对您有帮助。

awk -v var="-ilo." '{match($0,/gama1.com/);print substr($0,1,RSTART-1) var substr($0,RSTART,RLENGTH)}'  Input_file

说明: 现在使用解决方案添加说明。

awk -v var="-ilo." '                                        ##Creating variable named var and have its value as -ilo. as per OP request.
{
  match($0,/gama1.com/);                                    ##Using match utility of awk by which we could use a regex and could match the specific needed part of a line. Its pattern is match(var/line,regex). If regex has a match on a line then out of the box variables named RSTART and RLENGTH will be having values in it. Where RSTART will have the starting value of matching regex and RLENGTH will have the length of matched regex by match utility.
  print substr($0,1,RSTART-1) var substr($0,RSTART,RLENGTH) ##Printing the substring here which starts from 1st letter to till the value of RSTART-1(means just before the match) print everything then print variable var here then again print substring of line whose value starts from RSTART to RLENGTH to print the exact match in line.
}
' Input_file                                                ##Mentioning the Input_file name here.

答案 2 :(得分:2)

你可以试试这个sed

sed -E 's/([^.]*\.)(.*gama1.com$)/\1-ilo.\2/' infile

或者这个awk

awk '/gama1.com$/{sub(/\./,".-ilo.")}1' infile

答案 3 :(得分:1)

这是一个帖子,不是该怎么做,而是怎么做。

协调是王道:

     's/gama1.com/-ilo.gama1.com/g; 
   s/cdfgama1.com/-ilo.cdfgama1.com/g; 
  s/gg1-gama1.com/-ilo.gg1-gama1.com/g; 
 s/prod.gama1.com/-ilo.prod.gama1.com/g'

我们看到公共图案垂直对齐,可以分开公共部分和不常见部分。

's/(prod\.|gg1-|cdf)?gama1.com/-ilo.\1.gama1.com/g'

prod / gg1 / cdf只是随机的例子吗?我不知道。也许它只是一组小写字符和数字。替代品可以与OR:= |组合,但必须与parens组合,否则abc | def将匹配(abcef OR abdef),而不是(abc OR def)。随着parens的广泛使用,sed需要-r开关来扩展正则表达式,或者你必须掩盖parens:

's/(([a-z0-9]+\.)|([a-z0-9]+-)|([a-z0-9]+))?gama1.com/-ilo.\1.gama1.com/g'

这可以进一步浓缩为字母,可选地后跟点或负号:

 sed -r 's/(([a-z0-9]+)[.-]?)?gama1.com/-ilo.\2.gama1.com/g'

答案 4 :(得分:0)

对我来说perl代码看起来不错:

Edge.Func(SomeScript);