Linux
跳過用於重命名文件的 CSV 文件中的第一行(或更多行)
我已經使用 Stack Exchange 上另一個問題的資訊來允許我使用 csv 文件中的資訊重命名文件。此行允許我將所有文件從第 1 列中的名稱重命名為第 2 列中的名稱。
while IFS=, read -r -a arr; do mv "${arr[@]}"; done <$spreadsheet
但是,它會嘗試比較第一行中的資訊。我希望能夠包含一些允許我跳過行的程式碼。更好地理解上述程式碼行的工作原理也是很好的。我原以為它會包含一些關於列的資訊(即 A 和 B)
試試這個:
tail -n +2 $spreadsheet | while IFS=, read -r -a arr; do mv "${arr[@]}"; done
tail 命令只列印文件的最後幾行。使用“-n +2”,它從第二個開始列印文件的所有最後一行。
更多關於 while 循環。
mv
只要有可用的新行,while 循環就會執行該命令。它通過使用 while 循環的條件來做到這一點:IFS=, read -r -a arr
上面所做的是將一行讀入名為 的數組
arr
中,其中欄位分隔符 (IFS) 是一個逗號。-r
可能不需要該選項。然後,在執行
mv
命令時,“ $ {arr[@]}" is converted to the list of fields where each field is separated by double quotes. In your case, there are only two fields per line, so its expanded just to the two fields. The " $ {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.