简体   繁体   English

循环遍历目录内的文件

[英]looping over files inside directories

I have directories named 1, 2 and 3, each of them containing a file named OSZICAR .我有名为1, 2 and 3,目录1, 2 and 3,每个目录都包含一个名为OSZICAR的文件。 I want to create a file for plotting in gnuplot with 1st column as the directory names [1 2 3] and the second column as the characters from the last line of OSZICAR file.我想创建一个用于在 gnuplot 中绘图的文件,第一列作为目录名称 [1 2 3],第二列作为 OSZICAR 文件最后一行的字符。 I have tried the following code `我试过下面的代码`

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

But i am getting the the last of line of OSZICAR being copied only from one of the directory (named 1) and not other directories (2 and 3).但是我得到 OSZICAR 的最后一行仅从目录之一(名为 1)而不是其他目录(2 和 3)中复制。

Can anyone suggest an answer任何人都可以建议一个答案

No need to cd;无需光盘; also redirect outside loop:还重定向外循环:

for d in */;do

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

done >3.txt

A better way of doing it is using find command.更好的方法是使用find命令。

Try this尝试这个

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

Explanation :解释 :

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

You can try doing all of them in one loop.您可以尝试在一个循环中完成所有这些操作。

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