I have a variable like this:
words="这是一条狗。" I want to make a for loop on each of the characters, one at a time, e.g. first character="这", then character="是", character="一", etc.
The only way I know is to output each character to separate line in a file, then use while read line, but this seems very inefficient.
Example-2: Iterating a string variable using for loopCreate a bash file named 'for_list2.sh' and add the following script. Assign a text into the variable, StringVal and read the value of this variable using for loop.
$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.
In your case ## and %% are operators that extract part of the string. ## deletes longest match of defined substring starting at the start of given string. %% does the same, except it starts from back of the string.
You can use a C-style for loop:
foo=string for (( i=0; i<${#foo}; i++ )); do echo "${foo:$i:1}" done ${#foo} expands to the length of foo. ${foo:$i:1} expands to the substring starting at position $i of length 1.
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