Regex sed在mac地址中插入冒号

Regex sed在mac地址中插入冒号,regex,sed,Regex,Sed,我有以下格式的mac地址列表: 412010000018 412010000026 412010000034 我想要这个输出: 41:20:10:00:00:18 41:20:10:00:00:26 41:20:10:00:00:34 我尝试过这个,但没有成功: sed 's/([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})/\1:\2:\3:\4/g' mac_list 我应该怎么做?您必须使用正确的sed语法: \{I\} matches ex

我有以下格式的mac地址列表:

412010000018
412010000026
412010000034
我想要这个输出:

41:20:10:00:00:18
41:20:10:00:00:26
41:20:10:00:00:34
我尝试过这个,但没有成功:

sed 's/([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})/\1:\2:\3:\4/g' mac_list

我应该怎么做?

您必须使用正确的
sed
语法:

\{I\}
     matches exactly I sequences (I is a decimal integer;
     for portability, keep it between 0 and 255 inclusive).

\(REGEXP\)
     Groups the inner REGEXP as a whole, this is used for back references.
下面是一个涵盖前两个字段的示例命令

     sed 's/^\([0-9A-Fa-f]\{2\}\)\([0-9A-Fa-f]\{2\}\).*$/\1:\2:/'
以下命令可以处理完整的MAC地址,并且易于阅读:

 sed -e 's/^\([0-9A-Fa-f]\{2\}\)/\1_/'  \
     -e 's/_\([0-9A-Fa-f]\{2\}\)/:\1_/' \
     -e 's/_\([0-9A-Fa-f]\{2\}\)/:\1_/' \
     -e 's/_\([0-9A-Fa-f]\{2\}\)/:\1_/' \
     -e 's/_\([0-9A-Fa-f]\{2\}\)/:\1_/' \
     -e 's/_\([0-9A-Fa-f]\{2\}\)/:\1/'
按照@Qtax在此处发布的带有全局替换的perl解决方案的思想,可以得到一个更短的解决方案:

 sed -e 's/\([0-9A-Fa-f]\{2\}\)/\1:/g' -e 's/\(.*\):$/\1/'
awk 'BEGIN { FS= "" }
{ for (i=1; i<=length($0) ; i++) {
      if (i % 2 == 0) { macaddr=macaddr $i ":" } 
      else { macaddr = macaddr $i }
  }
  print gensub(":$","","g",macaddr)
  macaddr=""
}' INPUTFILE

如果
awk
是可接受的解决方案:

 sed -e 's/\([0-9A-Fa-f]\{2\}\)/\1:/g' -e 's/\(.*\):$/\1/'
awk 'BEGIN { FS= "" }
{ for (i=1; i<=length($0) ; i++) {
      if (i % 2 == 0) { macaddr=macaddr $i ":" } 
      else { macaddr = macaddr $i }
  }
  print gensub(":$","","g",macaddr)
  macaddr=""
}' INPUTFILE
awk'开始{FS=”“}
{对于(i=1;iPerl示例:

perl -pe 's/(\b|\G)[\da-f]{2}(?=[\da-f]{2})/$&:/ig' file
如果文件只有MAC地址,可以简化为:

perl -pe 's/\w{2}\B/$&:/g' file
这可能适用于您(GNU-sed):


这是对我有用的

sed 's/\(..\)/\1:/g;s/:$//' file

mac地址是十六进制格式,不仅仅是数字格式。一旦我开始使用基本数字格式,我还可以添加字母正则表达式