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?
$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.
${} 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.
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.
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.
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'
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