linux遍历目录(linux shell 遍历文件夹 并将结果保存 到变量)

本文目录
- linux shell 遍历文件夹 并将结果保存 到变量
- 在linux shell(bash)编程中,如何通过递归方式遍历文件
- linux平台:使用lua语言遍历某一文件夹下所有文件
- linux shell中的遍历目录并删除目录下与目录名相同的文件
- 怎么使用java编程实现linux下所有文件目录的遍历
- 一个linux下目录遍历函数,有个问题,chdir(dir);chdir(“..“)这两句为什么变更目录
- linux下遍历读取所有子目录里的特定文件,并改名复制到别的目录
- c语言怎么进入上一目录和下级目录
linux shell 遍历文件夹 并将结果保存 到变量
#!/bin/bash
(( $# 《 1 )) && echo "param is zero!" && exit 1
&& echo "$1 not path" && exit 1
dir=$1
dir_p="$dir Directory :"
cd $dir
dir=`pwd`
for i in `ls $dir`
do
if ; then
/tmp/sh/dir_file $i #我的脚本文件在/tmp/sh中,需要改一下这里
else
dir_p="$dir_p File $i"
fi
done
cd ..
echo $dir_p
实验结果:
# ./dir_file /tmp/python/
python_2 Directory : File 1.log File 2.log
python_3 Directory : File 3.log
/tmp/python/ Directory : File p File t.py File y.py
这样应该可以吧,试试看
在linux shell(bash)编程中,如何通过递归方式遍历文件
写一个函数,函数的参数是目录路径字符串
函数内使用 ls -s dir_path , 然后for 遍历循环
如果是目录则继续调用自身
如果是文件则答应文件名
从执行优化的角度来讲,可以把判断目录还是文件的代码放在循环外层.
好久没写shell了 ,我这也没环境测试 , 只能给个思路,函数的具体写法自己找一下资料吧.
另外,find命令可以直接完成你要做的事.
linux平台:使用lua语言遍历某一文件夹下所有文件
你可以参考如下实例代码:
function getFile(file_name)
local f = assert(io.open(file_name, ’r’))
local string = f:read("*all")
f:close()
return string
end function writeFile(file_name,string)
local f = assert(io.open(file_name, ’w’))
f:write(string)
f:close()
end --从命令行获取参数, 如果有参数则遍历指定目录,没有参数遍历当前目录 if arg ~= nil then
cmd = "ls "..arg
else
cmd = "ls" end print("cmd", cmd)
--io.popen 返回的是一个FILE,跟c里面的popen一样 local s = io.popen(cmd)
local fileLists = s:read("*all")
print(fileLists)
while true do --从文件列表里一行一行的获取文件名 _,end_pos, line = string.find(fileLists, "(+.txt)", start_pos)
if not end_pos then break end -- print ("wld", line) local str = getFile(line)
--把每一行的末尾 1, 替换为 0, local new =string.gsub(str, "1,\n", "0,\n");
--替换后的字符串写入到文件。以前的内容会清空 writeFile(line, new)
start_pos = end_pos + 1 end
linux shell中的遍历目录并删除目录下与目录名相同的文件
先设定实验环境:
#
造
5
个
目录,每个目录下,造
3
个
文件和两个子目录如下:
cd
$home/tmp
for
i
in
d1
d2
d3
d4
d5
do
mkdir
-p
$i
touch
$i/1.txt
$i/2.txt
$i/3.txt
mkdir
-p
$i/tmp1
$i/tmp2
done
#
检验测试环境:
$
ls
-lr
d1
total
0
-rw-r--r--
1
wenlee
comm
0
dec
22
10:35
1.txt
-rw-r--r--
1
wenlee
comm
0
dec
22
10:35
2.txt
-rw-r--r--
1
wenlee
comm
0
dec
22
10:35
3.txt
drwxr-sr-x
2
wenlee
comm
256
dec
22
10:35
tmp1/
drwxr-sr-x
2
wenlee
comm
256
dec
22
10:35
tmp2/
#
利用下列脚本来实现你要做的:
cd
$home/tmp
for
i
in
*/1.txt
do
echo
"found
$i,
save
$i
and
remove
everything
else
under
$(dirname
$i)/"
save_this_file=$(basename
$i)
curr_dir=$(dirname
$i)
#
把这个1.txt暂时存到/tmp里面去,为了避免已经有同样的档案名称在/tmp,加上$$
(i.e.
pid)
mv
$i
/tmp/${save_this_file}.$$
rm
-rf
$curr_dir
mkdir
-p
$curr_dir
mv
/tmp/${save_this_file}.$$
$curr_dir
done
#
屏幕执行输出如下:
found
d1/1.txt,
save
d1/1.txt
and
remove
everything
else
under
d1/
found
d2/1.txt,
save
d2/1.txt
and
remove
everything
else
under
d2/
found
d3/1.txt,
save
d3/1.txt
and
remove
everything
else
under
d3/
found
d4/1.txt,
save
d4/1.txt
and
remove
everything
else
under
d4/
found
d5/1.txt,
save
d5/1.txt
and
remove
everything
else
under
d5/
#
复验实验环境:
$
ls
-l
d?/*
-rw-r--r--
1
wenlee
comm
0
dec
22
10:35
d1/1.txt
-rw-r--r--
1
wenlee
comm
0
dec
22
10:35
d2/1.txt
-rw-r--r--
1
wenlee
comm
0
dec
22
10:35
d3/1.txt
-rw-r--r--
1
wenlee
comm
0
dec
22
10:35
d4/1.txt
-rw-r--r--
1
wenlee
comm
0
dec
22
10:35
d5/1.txt
ok?
thanks!
怎么使用java编程实现linux下所有文件目录的遍历
为了避免目录列举消耗时间过长,请指定一个目录来模拟,命令行参数:代表路径的字符串.
如果认可代码,请加分50,谢谢
----
import javax.swing.*;
import javax.swing.tree.*;
import java.awt.*;
import java.io.*;
final public class FileTree extends JFrame {
public FileTree(File dir) throws HeadlessException {
super("File Tree");
JTree tree;
add(new JScrollPane(tree =new JTree(buildTreeModel(dir))));
tree.setCellRenderer(new FileTreeRenderer());
setSize(400,600);
setVisible(true);
}
private TreeModel buildTreeModel(File dir){
DefaultMutableTreeNode root = new DefaultMutableTreeNode(dir);
walkthrough(dir,root);
return new DefaultTreeModel(root);
}
private static void walkthrough(File f,DefaultMutableTreeNode node){
for (File fle : f.listFiles()) {
DefaultMutableTreeNode n = new DefaultMutableTreeNode(fle);
node.add(n);
if (fle.isDirectory()){
walkthrough(fle, n);
}
}
}
private class FileTreeRenderer extends DefaultTreeCellRenderer {
public Component getTreeCellRendererComponent(JTree tree, Object value, boolean sel, boolean expanded, boolean leaf, int row, boolean hasFocus) {
JLabel cmp = (JLabel)super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf, row, hasFocus);
if (value instanceof DefaultMutableTreeNode) {
DefaultMutableTreeNode n = (DefaultMutableTreeNode)value;
Object obj = n.getUserObject();
if (obj instanceof File) {
File f = (File)obj;
cmp.setText(f.getName());
cmp.setForeground(f.isDirectory()?Color.BLUE:Color.BLACK);
}
}
return cmp;
}
}
public static void main(String args) {
new FileTree(new File(args));
}
}
一个linux下目录遍历函数,有个问题,chdir(dir);chdir(“..“)这两句为什么变更目录
因为为了让程序变得准确可行。
1、chdir("..");是为了在递归完某一子目录后,退回到其父目录继续遍历后续的普通文件或其他子目录;如果缺少这一语句,那么while循环中的递归printdir将会把父目录中后续的普通文件当作目录来操作,从而造成“无法打开目录”这种错误。
2、chdir(dir);是为了在程序刚运行时进入指定的目录,以及接下来递归时进入相应子目录;
用`pwd`提取的绝对路径。
$ more test1
#!/usr/bin/perl -w
# script name is test
use strict;
my $d="/home/gag";
my $now=`pwd`;
print $now,"\n";
chdir $d;
print `pwd`;print `ls`;
`touch iamhere`;
print "#######################\n";
chdir $now;print `pwd`;
`touch iamherethen`;
$ perl test1
/home/gag/perl/tmp
/home/gag
c
cpp1
cpp2
java
perl
shell
tools
#######################
/home/gag
$ ls
test1
$ ls ../../
c cpp1 cpp2 iamhere iamherethen java perl shell tools
linux下遍历读取所有子目录里的特定文件,并改名复制到别的目录
find . -name a.txt -exec mv {} b.txt \; 其中find后面的"."表示从当前目录开始查找(含子目录),注意最后的“\;"是需要的。
c语言怎么进入上一目录和下级目录
用C语言列出目录下的文件,在linux下可采用readdir(轿灶)函数来实现,代码实现过程为:
打开目录
循环读目录,输出目录下文件
关闭目录指针
参考代码:
#include 《dirent.h》
#include 《stdio.h》
int main()
{
DIR *dirp;
struct dirent *dp;
dirp = opendir("."); //打开目录指针
while ((dp = readdir(dirp)) != NULL) { //通过目录指针读目录
printf("%s\n", dp-》d_name );
}
(void) closedir(dirp); //关闭目录
return 0;
}
在windows下,代码如下:
#include 《io.h》
#include 《stdio.h》
void printDir( const char* path )
{
struct _finddata_t data;
long hnd = _findfirst( path, &data ); // 查找文件名与正则表达式chRE的匹配第一个文件
if ( hnd 《 0 )
{
perror( path );
}
int nRet = (hnd 《0 ) ? -1 : 1;
while ( nRet 》= 0 )
{
if ( data.attrib == _A_SUBDIR ) // 如果是目录
printf(" *\n", ***.name );
else
printf(" \n", ***.name );
nRet = _findnext( hnd, &data );
}
_findclose( hnd ); // 关闭当前句柄
}
void main()
{
printDir("d:/*.*");
}
相关函数说明:
long _findfirst( char *filespec, struct _finddata_t *fileinfo );
// 功 能 : 提供与filespec指定入口泛式匹配的第一个文件.通常后继用_findnext()函数来完成某泛式下的文件遍历.
// 头文件 : #include 《io.h》
// 参 数 : filespec - 目标文件规范,可以包含通配符
// fileinfo - 文件信息buffer
// 斗帆返回值 : 成功返回唯一的搜索句柄
// 出错返回-1,且设置errno为如下值:
// ENOENT 该泛式无法匹配
// EINVAL 无效文件名
int _findnext( long handle, struct _finddata_t *fileinfo );
// 功 能 : 按照前面_findfirst中的泛式规则,查找下一个符合该泛式的文件,并以此为依据修改fileinfo中的值
// 头文件 : #include 《io.h》
// 参 数 : long handle - 搜索句柄(通常由紧靠其前的_findfirst()返回)
// fileinfo - 文件信息buffer
// 返回值 : 成功返回0
// 出错返回-1
int _findclose( long handle );
// 功 能 : 关闭搜寻句柄并释放相应资源
// 头文件 : #include 《io.h》
// 参 数 : long handle - 搜索句柄(通常由紧靠其前的_findfirst()返回) 闭销扮
// 返回值 : 成功返回0
// 出错返回-1

更多文章:
linux遍历目录(linux shell 遍历文件夹 并将结果保存 到变量)
2026年9月11日 22:40
js解析url参数为对象(js如何获取请求中的url以及参数)
2026年9月11日 18:10
grad是什么意思啊(数学类)?android gradle 是什么文件
2026年9月11日 16:00
debugger javascript什么意思(javascript是什么意思)
2026年9月11日 14:00







