Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to perform a for loop on each character in a string in Bash?

Tags:

bash

for-loop

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.

  • How can I process each character in a string through a for loop?
like image 693
Village Avatar asked May 11 '12 13:05

Village


People also ask

How do I iterate through a string in bash?

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.

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 %% do in bash?

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.


1 Answers

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.

like image 110
chepner Avatar answered Sep 22 '22 03:09

chepner