[英]Remove leading zeros from MAC address
I have a MAC address that looks like this. 我有一个看起来像这样的MAC地址。
01:AA:BB:0C:D0:E1
I want to convert it to lowercase and strip the leading zeros. 我想将其转换为小写并去除前导零。
1:aa:bb:c:d0:e1
What's the simplest way to do that in a Bash script? 在Bash脚本中最简单的方法是什么?
$ echo 01:AA:BB:0C:D0:E1 | sed 's/\(^\|:\)0/\1/g;s/.*/\L\0/'
1:aa:bb:c:d0:e1
\\(^\\|:\\)0
represents either the line start ( ^
) or a :
, followed by a 0. We want to replace this by the capture (either line start or :
), which removed the 0
. \\(^\\|:\\)0
代表行首( ^
)或:
,后跟0。我们希望将其替换为捕获( 行首或:
,从而删除了0
。
Then, a second substitution ( s/.*/\\L\\0/
) put the whole line in lowercase. 然后,第二次替换( s/.*/\\L\\0/
)将整行都转换为小写。
$ sed --version | head -1
sed (GNU sed) 4.2.2
EDIT: Alternatively: 编辑:或者:
echo 01:AA:BB:0C:D0:E1 | sed 's/0\([0-9A-Fa-f]\)/\1/g;s/.*/\L\0/'
This replaces 0x
(with x
any hexa digit) by x
. 这将替换0x
(与x
任何六数字) x
。
EDIT: if your sed
does not support \\L
, use tr
: 编辑:如果您的sed
不支持\\L
,请使用tr
:
echo 01:AA:BB:0C:D0:E1 | sed 's/0\([0-9A-Fa-f]\)/\1/g' | tr '[:upper:]' '[:lower:]'
Here's a pure Bash≥4 possibility: 这是纯Bash≥4的可能性:
mac=01:AA:BB:0C:D0:E1
IFS=: read -r -d '' -a macary < <(printf '%s:\0' "$mac")
macary=( "${macary[@]#0}" )
macary=( "${macary[@],,}" )
IFS=: eval 'newmac="${macary[*]}"'
IFS=: read -r -d '' -a macary < <(printf '%s:\\0' "$mac")
is the canonical way to split a string into an array, IFS=: read -r -d '' -a macary < <(printf '%s:\\0' "$mac")
是将字符串拆分为数组的规范方法, "${macary[@]#0}"
is that of the array macary
with leading 0
(if any) removed, 扩展名"${macary[@]#0}"
是除去前导0
(如果有)的数组macary
, "${macary[@],,}"
is that of the array macary
in lowercase, 扩展名"${macary[@],,}"
是数组macary
的小写形式, IFS=: eval 'newmac="${macary[*]}"'
is a standard way to join the fields of an array (note that the use of eval
is perfectly safe). IFS=: eval 'newmac="${macary[*]}"'
是连接数组字段的标准方法(请注意,使用eval
是绝对安全的)。 After that: 之后:
declare -p newmac
yields 产量
declare -- newmac="1:aa:bb:c:d0:e1"
as required. 按要求。
A more robust way is to validate the MAC address first: 一种更可靠的方法是先验证MAC地址:
mac=01:AA:BB:0C:D0:E1
a='([[:xdigit:]]{2})' ; regex="^$a:$a:$a:$a:$a:$a$"
[[ $mac =~ $regex ]] || { echo "Invalid MAC address" >&2; exit 1; }
And then, using the valid result of the regex match (BASH_REMATCH): 然后,使用正则表达式匹配的有效结果(BASH_REMATCH):
set -- $(printf '%x ' $(printf '0x%s ' "${BASH_REMATCH[@]:1}" ))
IFS=: eval 'printf "%s\n" "$*"'
Which will print: 将打印:
1:aa:bb:c:d0:e1
Hex values without leading zeros and in lowercase. 不带前导零且十六进制的十六进制值。
If Uppercase is needed, change the printf '%x '
to printf '%X '
. 如果需要大写,请将printf '%x '
更改为printf '%X '
。
If Leading zeros are needed change the same to printf '%02x '
. 如果需要前导零,则将其更改为printf '%02x '
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.