ループ変数を保持しながら区切り文字で区切られた要素を抽出する

ループ変数を保持しながら区切り文字で区切られた要素を抽出する

私はbashの初心者であり、フレーズリストを繰り返そうとしています。私の目標は次のとおりです。

A)以下を.使用して各構文を分割します。

B)元のフレーズも使用できます。

私の疑似コード/試行は次のとおりです -

    while read x
    do
        eval "whole_phrase=$x" # store the whole phrase to another variable
        eval "first_element=echo $x | cut -d';' -f1" # extract the first element after splitting
        myprogram -i ../$first_element -o ../$whole_phrase
    done < ListOfDotSeparatedPhrases.txt

ListOfDotSeparatedPhrases.txtそれは次のとおりです -

18T3L.fastqAligned.sortedByCoord.out.bam
35T10R.fastqAligned.sortedByCoord.out.bam
18T6L.fastqAligned.sortedByCoord.out.bam
40T4LAligned.sortedByCoord.out.bam
22T10L.fastqAligned.sortedByCoord.out.bam
38T7L.fastqAligned.sortedByCoord.out.bam

私はこれを行うための最良の方法をウェブ上で検索しようとしましたが、失敗しました。どんなアイデアがありますか?私はこれが実際にそれほど難しくないと信じています!

ベストアンサー1

read分割してみましょう。フィールド区切り文字を設定するにはどうですか.

while IFS=. read -r first_element remainder; do 
  echo myprogram -i "../$first_element" -o "../${first_element}.${remainder}"
done < ListOfDotSeparatedPhrases.txt 
myprogram -i ../18T3L -o ../18T3L.fastqAligned.sortedByCoord.out.bam
myprogram -i ../35T10R -o ../35T10R.fastqAligned.sortedByCoord.out.bam
myprogram -i ../18T6L -o ../18T6L.fastqAligned.sortedByCoord.out.bam
myprogram -i ../40T4LAligned -o ../40T4LAligned.sortedByCoord.out.bam
myprogram -i ../22T10L -o ../22T10L.fastqAligned.sortedByCoord.out.bam
myprogram -i ../38T7L -o ../38T7L.fastqAligned.sortedByCoord.out.bam

からman bash

read [-ers] [-a aname] [-d delim] [-i text] [-n nchars] [-N nchars] [-p
       prompt] [-t timeout] [-u fd] [name ...]
              One line is read from the  standard  input,  or  from  the  file
              descriptor  fd  supplied  as an argument to the -u option, split
              into words as described above  under  Word  Splitting,  and  the
              first word is assigned to the first name, the second word to the
              second name, and so on.  If there are more words than names, the
              remaining words and their intervening delimiters are assigned to
              the last name.  If there are fewer words  read  from  the  input
              stream  than  names, the remaining names are assigned empty val‐
              ues.  The characters in IFS are used  to  split  the  line  into
              words  using  the  same  rules  the  shell  uses  for  expansion
              (described above under Word Splitting).


または(実際にはこれがより簡単で移植性が優れています)、行全体を読み取って保持し、シェル引数拡張を使用して残りの部分を削除して最初の要素を作成します。

while read -r x; do 
  myprogram -i "../${x%%.*}" -o "../$x"
done < ListOfDotSeparatedPhrases.txt

おすすめ記事