【问题标题】:looping content of a file to arguments将文件的内容循环到参数
【发布时间】:2018-11-04 09:55:38
【问题描述】:

所以你们都知道吗? Looping through the content of a file in Bash

所以我想做的是将文件的内容循环到参数。哪些更改输出等

我尝试了什么:

while read $1 & $2 & $3; do
#also tried:
#while read $1 $2 $3; do
    echo ${1}
    echo ${2}
    echo ${3}

    ./${1}.sh & ./${2}.sh & ./${3}.sh

done <file.txt

结果:

#arguments aren't echoed
./script.sh: line 31: ./.sh: No such file or directory
./script.sh: line 31: ./.sh: No such file or directory
./script.sh: line 31: ./.sh: No such file or directory
#scripts aren't executed

file.txt 内容

apple_fruit
#$1
apple_veggie
#$2
veggie_fruit
#$3
pear_fruit
#$1
pear_veggie
#$2
veggie_fruit
#$3

这样循环,在这种模式下^^

我也试过把文件改成这样:

apple_fruit apple_veggie veggie_fruit
pear_fruit pear_veggie veggie_fruit

简而言之:

我希望将 $1 替换为 apple_fruit,将 $2 替换为 apple_veggie,并将 $3 替换为 veggie_fruit。然后当它到达done 时,我希望它用 pear_fruit 替换 $1,用 pear_veggie 替换 $2,依此类推。

相关小问题

而且,为了让它工作,当你输入这个脚本时,你是否不添加任何参数

script.sh

或者你真的必须放一些东西,如果你做什么?因为争论总是会发生变化的。

script.sh mystery mystery mystery

【问题讨论】:

    标签: bash file loops arguments sh


    【解决方案1】:

    您可以使用 bash readarray builtin 将行读入数组 (line):

    readarray line < file.txt
    echo ${line[@]}
    

    输出:

    apple_fruit                                                              
    apple_veggie                                                             
    veggie_fruit                                                             
    pear_fruit                                                               
    pear_veggie                                                              
    veggie_fruit
    

    那你就可以了

    printf './%s.sh & '  "${line[@]}" | sed 's/ \& $//'         
    

    哪个输出

    ./apple_fruit.sh & ./apple_veggie.sh & ./veggie_fruit.sh & ./pear_fruit.sh & ./pear_veggie.sh & ./veggie_fruit.sh
    

    【讨论】:

      【解决方案2】:

      三行,三个reads:

      while IFS= read -r l1
            IFS= read -r l2
            IFS= read -r l3
      do
          echo "$l1, $l2, and $l3"
      done <<EOF
      apple_fruit
      apple_veggie
      veggie_fruit
      pear_fruit
      pear_veggie
      veggie_fruit
      EOF
      

      输出是

      apple_fruit, apple_veggie, and veggie_fruit
      pear_fruit, pear_veggie, and veggie_fruit
      

      这里没有真正的理由涉及位置参数;只需使用常规变量。

      【讨论】:

        猜你喜欢
        • 2020-10-14
        • 2017-12-19
        • 2010-12-04
        • 1970-01-01
        • 1970-01-01
        • 2016-07-26
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多