如何在for循环中跳过ls的第一个元素

时间:2020-08-14 17:54:54

标签: bash shell

我正在执行一条命令,该命令将我文件夹中的文件列表作为输入。所以我正在执行

cat <(for i in ls *chr*.txt; do echo $i; done)

但是,我不想包括该列表中的第一项。换句话说,我想跳过迭代1,所以我只有n-1个*chr*.txt文件。我该怎么做?

2 个答案:

答案 0 :(得分:8)

完全不要在这里使用ls。将文件放入数组,然后可以从第二个元素开始扩展数组。

files=( *chr*.txt )
printf '%s\n' "${files[@]:1}"

在不支持数组的基线POSIX外壳中,您可以将"$@"用于相同的目的,shift删除第一项:

set -- *chr*.txt    # put all names matching the pattern in $1/$2/...
shift               # remove $1, putting $2 in its place, moving $3 to $2, etc
printf '%s\n' "$@"  # print each item from our argument list on a separate line.

答案 1 :(得分:4)

不解析ls的输出。

您可以使用这种衬板:

for i in *chr*.txt; do ((first++)) && echo "$i"; done

或者使用数组:

# array holding matching files
arr=(*chr*.txt)

# loop through all but first file 
for i in "${arr[@]:1}"; do
    echo "$i"
done