简体   繁体   中英

looping over files inside directories

I have directories named 1, 2 and 3, each of them containing a file named 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. 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).

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM