ファイルの名前を変更するために使用されるCSVファイルの最初の行(またはそれ以上の行)をスキップする

ファイルの名前を変更するために使用されるCSVファイルの最初の行(またはそれ以上の行)をスキップする

csvファイルの情報を使用してファイル名を変更できるStack Exchangeの他の質問の情報を使用しました。この行を使用すると、列1の名前から列2の名前にすべてのファイルの名前を変更できます。

while IFS=, read -r -a arr; do mv "${arr[@]}"; done <$spreadsheet 

しかし、一番上の行の情報を比較しようとします。行をスキップできるコードを含めたいです。上記のコード行がどのように機能するかをよりよく理解することをお勧めします。私はそれが列(例えばAとB)に関するいくつかの情報を含むと思いました。

ベストアンサー1

この試み:

tail -n +2 $spreadsheet | while IFS=, read -r -a arr; do mv "${arr[@]}"; done

tail コマンドはファイルの最後の数行だけを出力します。 "-n+2" を使用すると、2 行目から始まり、ファイルの最後の行がすべて印刷されます。

whileループの詳細をご覧ください。mvwhileループは、新しい行が利用可能になるたびにコマンドを実行します。これは、whileループの条件文を使用して実行されます。

IFS=, read -r -a arr

arr上記の操作は、フィールド区切り記号(IFS)がコンマである配列で行を読み込みます。この-rオプションは不要な場合があります。

その後mv、コマンドを実行すると、「${arr[@]}」がフィールドのリストに変換されます。ここで、各フィールドは二重引用符で区切られます。あなたの場合、1行あたりのフィールドは2つだけなので、その2つのフィールドにのみ拡張されます。 「${arr[@]}」は、マニュアルで説明されているように、配列に対する bash の特別な規則です。

   Any element of an array may be referenced using ${name[subscript]}.  The braces are
   required  to  avoid conflicts with pathname expansion.  If subscript is @ or *, the
   word expands to all members of name.  These subscripts differ only  when  the  word
   appears  within double quotes.  If the word is double-quoted, ${name[*]} expands to
   a single word with the value of each array member separated by the first  character
   of the IFS special variable, and ${name[@]} expands each element of name to a sepa-
   rate word.  When there are no array members, ${name[@]} expands to nothing.  If the
   double-quoted  expansion occurs within a word, the expansion of the first parameter
   is joined with the beginning part of the original word, and the  expansion  of  the
   last  parameter  is joined with the last part of the original word.  This is analo-
   gous to the expansion of the special parameters * and  @  (see  Special  Parameters
   above).   ${#name[subscript]} expands to the length of ${name[subscript]}.  If sub-
   script is * or @, the expansion is the number of elements in the array.   Referenc-
   ing  an  array  variable  without  a subscript is equivalent to referencing element
   zero.

おすすめ記事