Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a String to all spaces in Bash?

For formatting purposes, I want to replace all characters of a String with spaces.

STR="some string of unknown length"
SPC="                             " <--- this is what I want

With help of this page, the best I could come up with is this:

SPC=${STR//[a-Z]/ }

But this only replaces letters, not digits or any special characters. What's the placeholder for "any character" with this type of Bash string replacements?

like image 806
dokaspar Avatar asked Dec 03 '15 15:12

dokaspar


People also ask

What does [- Z $1 mean in bash?

$1 means an input argument and -z means non-defined or empty. You're testing whether an input argument to the script was defined when running the script. Follow this answer to receive notifications.

What does ${} mean in bash?

${} Parameter Substitution/Expansion A parameter, in Bash, is an entity that is used to store values. A parameter can be referenced by a number, a name, or by a special symbol. When a parameter is referenced by a number, it is called a positional parameter.

How do I strip a string in bash?

Example-2: Trim string data using `sed` command `sed` command is another option to remove leading and trailing space or character from the string data. The following commands will remove the spaces from the variable, $myVar using `sed` command. Use sed 's/^ *//g', to remove the leading white spaces.


2 Answers

You can use:

str="some string of unknown length"
spc="${str//[^[:space:]]/ }"

[^[:space:]] will match any non-space character and replace it by space.

Verify:

echo "$str" | wc -c
30
echo "$spc" | wc -c
30

PS: You can also do:

spc="${str//?/ }"

to get the string of same length containing only spaces. ? matches any character in glob.

like image 158
anubhava Avatar answered Nov 03 '22 09:11

anubhava


This is an alternative (no regex/parsing at all) solution:

STR='some string of unknown length.' # Actually 30 chars
# Create an SCP var of the same length of STR filled with spaces (# updated implementation, thanks gniourf_gniourf)
printf -v SCP '%*s' ${#STR}

Test:

echo "${STR}"                 # 'some string of unknown length.'
echo "${SCP}"                 # '                              '
echo "Length STR -> ${#STR}"  # 'Length STR -> 30'
echo "Length SCP -> ${#SCP}"  # 'Length SCP -> 30'

How it works:

The printf command writes in variable SCP a string of at least the length equal to the number of chars of STR (${#STR}).

The tricks is in the s not replaced cause there is no further parameter after ${#STR}.

Usage example:

printf '%*s' 3       # '   '
printf '%*s' 3 .     # '  .'
printf '%*s' 3 123   # '123'
printf '%*s' 3 12345 # '12345'
like image 31
Giuseppe Ricupero Avatar answered Nov 03 '22 11:11

Giuseppe Ricupero