首页 文章

在Bash中循环遍历一串字符串?

提问于
浏览
1085

我想编写一个循环遍历15个字符串的脚本(可能是数组?)这可能吗?

就像是:

for databaseName in listOfNames
then
  # Do something
end

18 回答

  • -3

    您可以使用 ${arrayName[@]} 的语法

    #!/bin/bash
    # declare an array called files, that contains 3 values
    files=( "/etc/passwd" "/etc/group" "/etc/hosts" )
    for i in "${files[@]}"
    do
        echo "$i"
    done
    
  • 2

    试试这个 . 它正在运行和测试 .

    for k in "${array[@]}"
    do
        echo $k
    done
    
    # For accessing with the echo command: echo ${array[0]}, ${array[1]}
    
  • 96

    当然,这是可能的 .

    for databaseName in a b c d e f; do
      # do something like: echo $databaseName
    done
    

    有关详细信息,请参阅Bash Loops for, while and until .

  • 1

    简单方法:

    arr=("sharlock"  "bomkesh"  "feluda" )  ##declare array
    
    len=${#arr[*]}  # it returns the array length
    
    #iterate with while loop
    i=0
    while [ $i -lt $len ]
    do
        echo ${arr[$i]}
        i=$((i+1))
    done
    
    
    #iterate with for loop
    for i in $arr
    do
      echo $i
    done
    
    #iterate with splice
     echo ${arr[@]:0:3}
    
  • 33

    你可以像这样使用它:

    ## declare an array variable
    declare -a arr=("element1" "element2" "element3")
    
    ## now loop through the above array
    for i in "${arr[@]}"
    do
       echo "$i"
       # or do whatever with individual element of the array
    done
    
    # You can access them using echo "${arr[0]}", "${arr[1]}" also
    

    也适用于多行数组声明

    declare -a arr=("element1" 
                    "element2" "element3"
                    "element4"
                    )
    
  • 590

    脚本或函数的隐式数组:

    除了anubhava的正确答案:如果循环的基本语法是:

    for var in "${arr[@]}" ;do ...$var... ;done
    

    bash中有一个特例:

    当运行脚本或函数时,在命令行传递的 arguments 将被分配给 $@ 数组变量,您可以通过 $1$2$3 等进行访问 .

    这可以填充(用于测试)

    set -- arg1 arg2 arg3 ...
    

    loop over this 数组可以简单地写成:

    for item ;do
        echo "This is item: $item."
      done
    

    Note 保留的工作 in 不存在,也没有数组名称!

    样品:

    set -- arg1 arg2 arg3 ...
    for item ;do
        echo "This is item: $item."
      done
    This is item: arg1.
    This is item: arg2.
    This is item: arg3.
    This is item: ....
    

    请注意,这与

    for item in "$@";do
        echo "This is item: $item."
      done
    

    然后进入一个脚本:

    #!/bin/bash
    
    for item ;do
        printf "Doing something with '%s'.\n" "$item"
      done
    

    将其保存在脚本 myscript.shchmod +x myscript.sh 中,然后

    ./myscript.sh arg1 arg2 arg3 ...
    Doing something with 'arg1'.
    Doing something with 'arg2'.
    Doing something with 'arg3'.
    Doing something with '...'.
    

    在函数中相同:

    myfunc() { for item;do cat <<<"Working about '$item'."; done ; }
    

    然后

    myfunc item1 tiem2 time3
    Working about 'item1'.
    Working about 'tiem2'.
    Working about 'time3'.
    
  • 7

    Yes

    for Item in Item1 Item2 Item3 Item4 ;
      do
        echo $Item
      done
    

    输出:

    Item1
    Item2
    Item3
    Item4
    

    Over multiple lines

    for Item in Item1 \
                Item2 \
                Item3 \
                Item4
      do
        echo $Item
      done
    

    输出:

    Item1
    Item2
    Item3
    Item4
    

    Simple list variable

    List=( Item1 Item2 Item3 )
    

    要么

    List=(
          Item1 
          Item2 
          Item3
         )
    

    Display the list variable :

    echo ${List[*]}
    

    出局:

    Item1 Item2 Item3
    

    Loop through the list:

    for Item in ${List[*]} 
      do
        echo $Item 
      done
    

    出局:

    Item1
    Item2
    Item3
    

    Create a function to go through a list:

    Loop(){
      for item in ${*} ; 
        do 
          echo ${item} 
        done
    }
    Loop ${List[*]}
    

    To preserve spaces ; single or double quote list entries and double quote list expansions :

    List=(' Item 1 '
          ' Item 2' 
          ' Item 3'
         )
    for item in "${List[@]}"; 
      do 
        echo "$item"
      done
    

    输出:

    Item 1
     Item 2
     Item 3
    

    Using the declare keyword (command) to create the list , which is technically called an array :

    declare -a List=(
                     "element 1" 
                     "element 2" 
                     "element 3"
                    )
    for entry in "${List[@]}"
       do
         echo "$entry"
       done
    

    出局:

    element 1
    element 2
    element 3
    

    Creating an associative array . A dictionary :

    declare -A continent
    
    continent[Vietnam]=Asia
    continent[France]=Europe
    continent[Argentina]=America
    
    for item in "${!continent[@]}"; 
      do
        printf "$item is in ${continent[$item]} \n"
      done
    

    输出:

    Argentina is in America
     Vietnam is in Asia
     France is in Europe
    

    CVS variables or files in to a list .
    将内部字段分隔符从空格更改为您想要的任何内容 .
    在下面的示例中,它将更改为逗号

    List="Item 1,Item 2,Item 3"
    Backup_of_internal_field_separator=$IFS
    IFS=,
    for item in $List; 
      do
        echo $item
      done
    IFS=$Backup_of_internal_field_separator
    

    输出:

    Item 1
    Item 2
    Item 3
    

    If need to number them :

    `
    

    这被称为后退 . 将命令放在后面 .

    `commend`
    

    它位于键盘上的第一个旁边,或者位于Tab键上方 . 在标准的美国英语键盘上 .

    List=()
    Start_count=0
    Step_count=0.1
    Stop_count=1
    for Item in `seq $Start_count $Step_count $Stop_count`
        do 
           List+=(Item_$Item)
        done
    for Item in ${List[*]}
        do 
            echo $Item
        done
    

    输出是:

    Item_0.0
    Item_0.1
    Item_0.2
    Item_0.3
    Item_0.4
    Item_0.5
    Item_0.6
    Item_0.7
    Item_0.8
    Item_0.9
    Item_1.0
    

    Becoming more familiar with bashes behavior :

    在文件中创建列表

    cat <<EOF> List_entries.txt
    Item1
    Item 2 
    'Item 3'
    "Item 4"
    Item 7 : *
    "Item 6 : * "
    "Item 6 : *"
    Item 8 : $PWD
    'Item 8 : $PWD'
    "Item 9 : $PWD"
    EOF
    

    将列表文件读入列表并显示

    List=$(cat List_entries.txt)
    echo $List
    echo '$List'
    echo "$List"
    echo ${List[*]}
    echo '${List[*]}'
    echo "${List[*]}"
    echo ${List[@]}
    echo '${List[@]}'
    echo "${List[@]}"
    

    BASH commandline reference manual : Special meaning of certain characters or words to the shell.

  • 4

    如果您使用的是Korn shell,则有“ set -A databaseName ", else there is " declare -a databaseName

    编写一个处理所有shell的脚本,

    set -A databaseName=("db1" "db2" ....) ||
            declare -a databaseName=("db1" "db2" ....)
    # now loop 
    for dbname in "${arr[@]}"
    do
       echo "$dbname"  # or whatever
    
    done
    

    它应该适用于所有炮弹 .

  • 4

    本着与4ndrew的回答一样的精神:

    listOfNames="RA
    RB
    R C
    RD"
    
    # To allow for other whitespace in the string:
    # 1. add double quotes around the list variable, or
    # 2. see the IFS note (under 'Side Notes')
    
    for databaseName in "$listOfNames"   #  <-- Note: Added "" quotes.
    do
      echo "$databaseName"  # (i.e. do action / processing of $databaseName here...)
    done
    
    # Outputs
    # RA
    # RB
    # R C
    # RD
    

    B.名字中没有空格:

    listOfNames="RA
    RB
    R C
    RD"
    
    for databaseName in $listOfNames  # Note: No quotes
    do
      echo "$databaseName"  # (i.e. do action / processing of $databaseName here...)
    done
    
    # Outputs
    # RA
    # RB
    # R
    # C
    # RD
    

    Notes

    • 在第二个示例中,使用 listOfNames="RA RB R C RD" 具有相同的输出 .

    引入数据的其他方式包括:

    从stdin读取

    # line delimited (each databaseName is stored on a line)
    while read databaseName
    do
      echo "$databaseName"  # i.e. do action / processing of $databaseName here...
    done # <<< or_another_input_method_here
    
    • bash IFS "field separator to line" [1]分隔符可以在脚本中指定以允许其他空格(即 IFS='\n' ,或MacOS IFS='\r'

    • 我也喜欢接受的答案:) - 我已经将这些片段作为其他有用的方式包含在内,也可以回答这个问题 .

    • 在脚本文件的顶部包含 #!/bin/bash 表示执行环境 .

    • 花了几个月的时间才弄清楚如何编写这个简单:)

    其他来源(while read loop

  • 1740

    这类似于user2533809的答案,但每个文件将作为单独的命令执行 .

    #!/bin/bash
    names="RA
    RB
    R C
    RD"
    
    while read -r line; do
        echo line: "$line"
    done <<< "$names"
    
  • 44

    单线循环,

    declare -a listOfNames=('db_a' 'db_b' 'db_c')
     for databaseName in ${listOfNames[@]}; do echo $databaseName; done;
    

    你会得到这样的输出,

    db_a
    db_b
    db_c
    
  • 152

    我遍历我的项目数组以进行 git pull 更新:

    #!/bin/sh
    projects="
    web
    ios
    android
    "
    for project in $projects do
        cd  $HOME/develop/$project && git pull
    end
    
  • 2

    声明数组不适用于Korn shell . 对Korn shell使用以下示例:

    promote_sla_chk_lst="cdi xlob"
    
    set -A promote_arry $promote_sla_chk_lst
    
    for i in ${promote_arry[*]};
        do
                echo $i
        done
    
  • 18

    每个Bash脚本/会话可能的第一行:

    say() { for line in "${@}" ; do printf "%s\n" "${line}" ; done ; }
    

    使用例如:

    $ aa=( 7 -4 -e ) ; say "${aa[@]}"
    7
    -4
    -e
    

    可以考虑: echo-e 解释为此处的选项

  • 1

    这些答案都不包括反击......

    #!/bin/bash
    ## declare an array variable
    declare -a array=("one" "two" "three")
    
    # get length of an array
    arraylength=${#array[@]}
    
    # use for loop to read all values and indexes
    for (( i=1; i<${arraylength}+1; i++ ));
    do
      echo $i " / " ${arraylength} " : " ${array[$i-1]}
    done
    

    输出:

    1  /  3  :  one
    2  /  3  :  two
    3  /  3  :  three
    
  • 4
    listOfNames="db_one db_two db_three"
    for databaseName in $listOfNames
    do
      echo $databaseName
    done
    

    要不就

    for databaseName in db_one db_two db_three
    do
      echo $databaseName
    done
    
  • 1

    这也很容易阅读:

    FilePath=(
        "/tmp/path1/"    #FilePath[0]
        "/tmp/path2/"    #FilePath[1]
    )
    
    #Loop
    for Path in "${FilePath[@]}"
    do
        echo "$Path"
    done
    
  • 0

    很惊讶没有人发布这个 - 如果你在循环数组时需要元素的索引,你可以这样做:

    arr=(foo bar baz)
    
    for i in ${!arr[@]}
    do
        echo $i "${arr[i]}"
    done
    

    输出:

    0 foo
    1 bar
    2 baz
    

    我发现这比"traditional" for-loop风格( for (( i=0; i<${#arr[@]}; i++ )) )更优雅 .

    ${!arr[@]}$i 不仅仅是数字;有些人会建议引用它们,但这只是个人偏好 . )

相关问题