Score:0

Centering a string in another

jp flag

I am using Ubuntu 18.04

I have a string of length N which I want to center in another string.

Thus setting some string of length N

old_string="***"

I want a new string (length 55) with the old string centered in it.

new_string="     ***     "

How can I do this in bash ?

Although in actual fact the trailing spaces are redundant, so I can-simply have

new_string="     ***"
ar flag
Which distro and version of Linux are you using?
jp flag
Am using Ubuntu 18.04
hr flag
You could do essentially the same as this, but with a fixed value 55 in place of the `COLUMNS` variable: [Ubuntu 16.04 : Center greeting command in terminal](https://askubuntu.com/a/818207/178692)
Score:0
bs flag
knu

Assuming you use the bash shell, try this:

short='---' 
long='abcdefgh'
half=$(( ${#long} / 2 ))
result=${long:0:${half}}${short}${long:${half}}
printf "%s\n" $short $long $half $result

Result:

---
abcdefgh
4
abcd---efgh

Reference:

man bash
/ Parameter Expansion
I sit in a Tesla and translated this thread with Ai:

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.