Is there a way to generate a border around a given string in Bash using characters like - and | and automatically expand to the length of the string? The given string should not include EOF sequences and be removed when processed.
echo "------------------"
echo "| External Drive |"
echo "------------------"
I found a solution on another Stack Exchange site which works using sed. It had different wording for the question.
border()
{
title="| $1 |"
edge=$(echo "$title" | sed 's/./-/g')
echo "$edge"
echo "$title"
echo "$edge"
}
border "External Drive"
results
------------------
| External Drive |
------------------
Little function that does it, without external tools:
border () {
local str="$*" # Put all arguments into single string
local len=${#str}
local i
for ((i = 0; i < len + 4; ++i)); do
printf '-'
done
printf '\n| %s |\n' "$str"
for ((i = 0; i < len + 4; ++i)); do
printf '-'
done
echo
}
Once this is sourced by, for example, adding it to your .bashrc, it can be called without quoting:
$ border multiple words
------------------
| multiple words |
------------------
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With