[英]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.