2

How you can get the first three parts from MAC address?

$ mac=11:22:33:44:55:66
$ vendor=${${mac//:/}:0:6}
bash: ${${mac//:/}:0:6}: bad substitution

${mac//:/} removes : and :0:6 should get the first 6 characters?

or other way around:

vendor=${${mac:0:8}//:/}
bash: ${${mac:0:8}//:/}: bad substitution

Expected: 112233. What's the correct syntax?

This works but needs two assignments:

vendor=${mac//:/}
vendor=${vendor:0:6}
echo $vendor
112233

Can you do this with one line with only bash?

GNU bash version is 5.1.0

2
  • Use parameter expansion to modify output of another expansion Commented Mar 17, 2021 at 10:11
  • "Can you do this with one line with only bash?" -- sure: vendor=${mac//:/}; vendor=${vendor:0:6}; echo "$vendor". But really, is it such a big issue to use the temporary? Commented Mar 17, 2021 at 10:13

2 Answers 2

4

with bash you already have the solution, and it requires two assignments but if you just need the output you can omit the second assignment and directly output the result as bash yet doesn't support nested parameter substitution (maybe in the future it will).

$ mac='11:22:33:44:55:66'
$ vendor=${mac//:}
$ echo ${vendor::6}

Or use cut instead for short:

cut -d: -f1,2,3 --output-delimiter= <<<"$mac"
2

You can use awk as well:

$ mac=11:22:33:44:55:66
$ echo "$mac" | awk -F':' '{ print $1""$2""$3}'
112233

About the nested parameter expansion, check this answer:

Can a parameter expansion work inside another parameter expansion?

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.