[英]Loop through certain lines of files in home directory in bash
I want to loop through a certain range of file lines in my home directory.我想遍历我的主目录中的某个范围的文件行。 Eg I have 10 lines of files in my home directory and I want to loop through the 2nd to the 9th file line and print them to the terminal.
例如,我的主目录中有 10 行文件,我想遍历第 2 到第 9 行文件并将它们打印到终端。
For example, my home directory:例如,我的主目录:
/home/
--file1.txt
--file2.txt
.
.
--file9.txt
--file10.txt
I want to print the filenames: file2.txt all the way through to file9.txt我想打印文件名:file2.txt 一直到 file9.txt
How can I do such thing?我怎么能做这样的事情?
Yet another way:还有一种方式:
ls -1|sed -n 2,9p
Note that the ls
option above is 1
, not l
.请注意,上面的
ls
选项是1
,而不是l
。
First you could create an array as首先你可以创建一个数组
for a in $(ls); do array[$i]=$a; i=$(($i+1)); done
and then reference the range desired as (for items 2 through 9)然后引用所需的范围(对于项目 2 到 9)
echo ${array[@]:1:10}
There's probably a more elegant way to fill the array.可能有一种更优雅的方式来填充数组。
#!/bin/bash
cnt=0 # Initialise a variable cnt
for i in *;
do
cnt=$((cnt+1)); # Loop through each filename which is read in as a variable i and increment the cnt variable.
if [[ "$cnt" == "2" || "$cnt" == "9" ]];
then
echo $i; # If the cnt variable is 2 or 9, print the filename
fi;
done
It's generally a bad idea to parse ls
output , because weird characters in filenames can cause hard-to-parse output -- use a wildcard (like *
) instead.解析
ls
output 通常是个坏主意,因为文件名中的奇怪字符会导致难以解析 output —— 改用通配符(如*
)。 In bash, it's easy to capture the result of a wildcard expansion to an array, and then you can iterate over the array (or a selected part of it).在 bash 中,很容易捕获通配符扩展到数组的结果,然后您可以遍历数组(或其中的选定部分)。 Here's an example getting files from the current working directory (not necessarily your home directory):
这是从当前工作目录(不一定是您的主目录)获取文件的示例:
files=(*)
for file in "${files[@]:2:8}"; do # 8 items starting at #2 = #2 through #9
echo "$file" # or whatever
done
Now, if you want files from your home directory, you have to specify the path as part of the wildcard pattern, and the results you get will include that path (eg you'd get something like "/home/johnboy/file1.txt" instead of just "file1.txt").现在,如果你想从你的主目录中获取文件,你必须指定路径作为通配符模式的一部分,你得到的结果将包括那个路径(例如你会得到类似“/home/johnboy/file1.txt ” 而不仅仅是“file1.txt”)。 If you want just the name, you have to remove the path part:
如果您只想要名称,则必须删除路径部分:
files=(~/*)
for file in "${files[@]:2:8}"; do
echo "${file##*/}" # the ##*/ modifier removes the path prefix
done
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.