簡體   English   中英

遍歷 bash 主目錄中的某些文件行

[英]Loop through certain lines of files in home directory in bash

我想遍歷我的主目錄中的某個范圍的文件行。 例如,我的主目錄中有 10 行文件,我想遍歷第 2 到第 9 行文件並將它們打印到終端。

例如,我的主目錄:

/home/
--file1.txt
--file2.txt
   .
   .
--file9.txt
--file10.txt

我想打印文件名:file2.txt 一直到 file9.txt

我怎么能做這樣的事情?

還有一種方式:

ls -1|sed -n 2,9p

請注意,上面的ls選項是1 ,而不是l

首先你可以創建一個數組

for a in $(ls); do array[$i]=$a; i=$(($i+1)); done

然后引用所需的范圍(對於項目 2 到 9)

echo ${array[@]:1:10}

可能有一種更優雅的方式來填充數組。

#!/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

解析ls output 通常是個壞主意,因為文件名中的奇怪字符會導致難以解析 output —— 改用通配符(如* )。 在 bash 中,很容易捕獲通配符擴展到數組的結果,然后您可以遍歷數組(或其中的選定部分)。 這是從當前工作目錄(不一定是您的主目錄)獲取文件的示例:

files=(*)
for file in "${files[@]:2:8}"; do    # 8 items starting at #2 = #2 through #9
    echo "$file"    # or whatever
done

現在,如果你想從你的主目錄中獲取文件,你必須指定路徑作為通配符模式的一部分,你得到的結果將包括那個路徑(例如你會得到類似“/home/johnboy/file1.txt ” 而不僅僅是“file1.txt”)。 如果您只想要名稱,則必須刪除路徑部分:

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM