Bash 我希望能够从一行中提取两个不同的序列

Bash 我希望能够从一行中提取两个不同的序列,bash,for-loop,while-loop,Bash,For Loop,While Loop,我希望能够从一行中提取两个不同的序列 例如: atgttg tca aat tca tgg atc atg ttg tca aat tca tgg atctag 我想创建一个循环,程序将从第一个atg读取到标记,将该序列输出到一个文件中,并将第二个atg读取到标记,将该序列输出到同一个文件中 我想要的输出: atg ttg tca aat tca tgg atc atg ttg tca aat tca tgg atc tag atg ttg tca aat tca tgg atc tag 我该

我希望能够从一行中提取两个不同的序列

例如:

atgttg tca aat tca tgg atc atg ttg tca aat tca tgg atctag

我想创建一个循环,程序将从第一个atg读取到标记,将该序列输出到一个文件中,并将第二个atg读取到标记,将该序列输出到同一个文件中

我想要的输出:

atg ttg tca aat tca tgg atc atg ttg tca aat tca tgg atc tag
atg ttg tca aat tca tgg atc tag
我该怎么办


谢谢您的帮助。

请尝试以下操作:

str="atg ttg tca aat tca tgg atc atg ttg tca aat tca tgg atc tag"
start="atg"    # start marker of the sequence
end="tag"      # end marker of the sequence

read -r -a ary <<< "$str"
for (( i=0; i<${#ary[@]}; i++ )); do
    if [[ ${ary[$i]} = $start ]]; then
        index_s+=("$i")
    elif [[ ${ary[$i]} = $end ]]; then
        index_e+=("$i")
    fi
done

s=${index_s[0]}; n=$(( ${index_e[0]} - ${index_s[0]} + 1 ))
echo "${ary[@]:$s:$n}" > "result.txt"
s=${index_s[1]}; n=$(( ${index_e[0]} - ${index_s[1]} + 1 ))
echo "${ary[@]:$s:$n}" >> "result.txt"
[如何工作]


  • read-r-a ary当您最多需要2个序列时,您可以
    grep
    在原始字符串和修改后的字符串中:

    s='atg ttg tca aat tca tgg atc atg ttg tca aat tca tgg atc tag'
    printf "%s\n" "$s" "${s#*atg}" | grep -Eo "atg.*tag"
    
    如果要在可用时提取2个以上的子字符串,则需要一个循环

    s='atg ttg tca aat tca tgg atc atg ttg tca aat tca tgg atc tag'
    while [ "$s" ]; do
       s=$(grep -Eo "atg.*tag" <<< "$s")
       if [ "$s" ]; then
          echo "$s"
          s="${s#atg}"
       fi
    done
    
    s='atg ttg tca aat tca tgg atc atg ttg tca aat tca tgg atc标签'
    而[“$s”];做
    
    s=$(grep-Eo“atg.*tag”输出是什么?您尝试过什么?理想情况下,输出是:atg ttg tca aat tca tgg atc atg ttg tca aat tca tgg atc tag&atg ttg tca aat tca tgg atc tag。我是一个使用bash的初学者。我没有尝试过任何东西,因为我不知道如何解决这个问题:/
    s='atg ttg tca aat tca tgg atc atg ttg tca aat tca tgg atc tag'
    while [ "$s" ]; do
       s=$(grep -Eo "atg.*tag" <<< "$s")
       if [ "$s" ]; then
          echo "$s"
          s="${s#atg}"
       fi
    done