Shell(Bash)编程实例之获取某个文件夹下的所有文件名(含文件夹)

本文介绍如何使用Shell脚本获取指定文件夹下所有文件名,并去除文件后缀。同时展示了如何将输出重定向到文件及增加用户交互功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1. 获取某个文件夹下的所有文件名(含文件夹),并显示

#!/bin/sh  
#============ get the file name ===========  
Folder_A="/home/youname/shell/gotfilename/bin"  
for file_a in ${Folder_A}/*
do  
    temp_file=`basename $file_a`  
    echo $temp_file  
done        


若要去掉文件名的后缀(假 如该文件夹下的所有文件为.txt格式),则代码为

#!/bin/sh  
#============ get the file name ===========  
Folder_A="/home/youname/shell/gotfilename/bin"  
for file_a in ${Folder_A}/*
do  
    temp_file=`basename $file_a  .txt`  
    echo $temp_file  
done        


2.如果要输出到一个文件的话也可以重定向到一个文件中去

修改为:

#!/bin/sh  
#============ get the file name ===========  
Folder_A="/home/Neo/shell/gotfilename/bin"  
Output_file="output.txt"  
#这里用于清空原本的输出文件,感觉 : 这个符号用处挺大,shell的学习还是要多用才是  
: > $Output_file                                                                                                                                            
for file_a in ${Folder_A}/*
do  
    temp_file=`basename $file_a`  
    echo $temp_file >> $Output_file  
done  



3.增加了交互性

#!/bin/sh  
#============ get the file name ===========  
echo -e "请输入你要读取的文件夹路径\n当前路径为${PWD}"  
read InputDir  
echo "你输入的文件夹路径为${InputDir}"  
echo -e "请输入你要将数据输出保存的文件路径n当前路径为${PWD}"  
read OutputFile    
echo "输出保存的文件路径为${OutputFile}"  
: > $OutputFile   #清空OutputFile  
#循环读取文件夹名  
for file_a in ${InputDir}/*
 do  
    temp_file=`basename $file_a`  
    echo $temp_file >> $OutputFile  
done  



转载自:http://blog.youkuaiyun.com/beckdon/article/details/23945623

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值