【问题标题】:Shell script to find possible string sequences用于查找可能的字符串序列的 Shell 脚本
【发布时间】:2017-01-18 18:41:16
【问题描述】:

我有一个格式如下的文本文件:

苹果

一只蚂蚁

B 蝙蝠

B 球

每个字符的定义数可以是任意数。

我正在编写一个 shell 脚本,它将接收诸如“A B”之类的输入。我期待的 shell 脚本的输出是可以创建的可能的字符串序列。

对于输入“A B”,输出将是:

苹果蝙蝠

苹果球

蚂蚁蝙蝠

蚂蚁球

我尝试了 arrays,它没有按预期工作。任何人都可以提供有关如何解决此问题的一些想法吗?

【问题讨论】:

    标签: bash shell unix sh


    【解决方案1】:

    使用关联数组来完成此操作:

    #!/usr/bin/env bash
    
    first_letter=$1
    second_letter=$2
    
    declare -A words                  # declare associative array
    while read -r alphabet word; do   # read ignores blank lines in input file
      words+=(["$word"]="$alphabet")  # key = word, value = alphabet
    done < words.txt
    
    for word1 in "${!words[@]}"; do
      alphabet1="${words[$word1]}"
      [[ $alphabet1 != $first_letter ]] && continue
      for word2 in "${!words[@]}"; do
        alphabet2="${words[$word2]}"
        [[ $alphabet2 != $second_letter ]] && continue
        printf "$word1 $word2\n"              # print matching word pairs
      done
    done
    

    AB 作为参数传入的输出(包含您问题中的内容):

    Apple Ball
    Apple Bat
    Ant Ball
    Ant Bat
    

    您可能需要参考这篇文章以获取有关关联数组的更多信息: Appending to a hash table in Bash

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-11-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-06
      • 2013-11-13
      • 1970-01-01
      相关资源
      最近更新 更多