我使用了 Stack Exchange 上另一个问题的信息,允许我使用 csv 文件中的信息重命名文件。此行允许我将所有文件从第 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”,它会从第二行开始打印文件的所有最后一行。
更多关于 while 循环的内容。mv
只要有新行可用,while 循环就会运行该命令。它通过使用 while 循环的条件来实现这一点:
IFS=, read -r -a arr
上面的操作是将一行读入名为 的数组中arr
,其中字段分隔符 (IFS) 是逗号。该-r
选项可能不需要。
然后,运行mv
命令时,“${arr[@]}”将转换为字段列表,其中每个字段用双引号分隔。在您的情况下,每行只有两个字段,因此它仅扩展到这两个字段。 “${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.