nei*_*ilH 4 linux command-line scripting bash shell-script
我使用了 Stack Exchange 上另一个问题的信息,允许我使用 csv 文件中的信息重命名文件。此行允许我将所有文件从第 1 列中的名称重命名为第 2 列中的名称。
while IFS=, read -r -a arr; do mv "${arr[@]}"; done <$spreadsheet
Run Code Online (Sandbox Code Playgroud)
但是,它会尝试比较顶行中的信息。我希望能够包含一些允许我跳过行的代码。更好地理解上述代码行的工作方式也很好。我原以为它会包含一些关于列的信息(即 A 和 B)
尝试这个:
tail -n +2 $spreadsheet | while IFS=, read -r -a arr; do mv "${arr[@]}"; done
Run Code Online (Sandbox Code Playgroud)
tail 命令仅打印文件的最后几行。使用“-n +2”,它从第二行开始打印文件的所有最后一行。
更多关于 while 循环。mv只要有新行可用,while 循环就会运行命令。它通过使用 while 循环的条件来做到这一点:
IFS=, read -r -a arr
Run Code Online (Sandbox Code Playgroud)
上面所做的是将一行读入名为 的数组中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.
Run Code Online (Sandbox Code Playgroud)