簡體   English   中英

循環遍歷目錄內的文件

[英]looping over files inside directories

我有名為1, 2 and 3,目錄1, 2 and 3,每個目錄都包含一個名為OSZICAR的文件。 我想創建一個用於在 gnuplot 中繪圖的文件,第一列作為目錄名稱 [1 2 3],第二列作為 OSZICAR 文件最后一行的字符。 我試過下面的代碼`

for d in */;do

    echo "$d">>1.txt

done

# to avoid the slash and get 1 2 3 values only
cut -c -1,3 1.txt >2.txt

for d in */;do

    cd $d | tail -n 1 OSZICAR | cut -c9-22>3.txt

done

paste 2.txt 3.txt > gnu.text

但是我得到 OSZICAR 的最后一行僅從目錄之一(名為 1)而不是其他目錄(2 和 3)中復制。

任何人都可以建議一個答案

無需光盤; 還重定向外循環:

for d in */;do

    tail -n 1 $d/OSZICAR | cut -c9-22

done >3.txt

更好的方法是使用find命令。

嘗試這個

find . -type f  -name   OSZICAR  -exec tail -n 1 {} ';' | cut -c9-22

解釋 :

find 
.  <--  Means current directory  
-type f <--- Should be file 
 -name   OSZICAR <--  File name should be OSZICAR  
-exec <--  Execute command on output of find  
tail -n 1 
{} ';' <-- ; tells where command is ending  
| cut -c9-22

您可以嘗試在一個循環中完成所有這些操作。

#!/usr/bin/env bash

directories=({1..3}/)

for d in "${directories[@]}"; do
  if [[ -f ${d}OSZICAR ]]; then
    chars=$(tail -n1 "${d}OSZICAR" | cut -c9-22)
    printf '%s\t %s\n' "${d%/*}" "$chars"
  fi
done > gnu.text

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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