如何从 BOURNE SHELL 中的字符串中提取 n 个字符?

How to extract n character from string in BOURNE SHELL?

我想从 bourne shell 中的字符串中提取一个包含 n 个字符的子字符串。 这是我的例子:

#!/bin/sh
MAC=XX:XX:XX:XX:XX:XX

Result: 

MAC_SUBSTR=XX:XX:XX:X

使用cut切割部分刺。

mac_substr=$(printf "%s\n" "$mac" | cut -b 1-9)

喜欢在脚本中使用小写变量。用 shellcheck 检查你的脚本。


您使用“Bourne Shell”的可能性非常小。它不再在任何地方使用。 POSIX sh 的常见关闭实现是 dash(我认为现在在 ubuntu 中使用)和 Busybox ash(alpine linux),其中 ash 支持变量扩展提取子串:

mac_substr=${mac:1:9}

dash不支持