簡體   English   中英

Bash腳本獲取具有所需擴展名的所有文件

[英]Bash script to get all file with desired extensions

我正在嘗試編寫一個bash腳本,如果我傳遞包含擴展名的文本文件,並且文件夾向我返回了輸出文件,其中包含與所需擴展名匹配的所有文件的列表,則在所有子目錄中進行遞歸搜索

該文件夾是我的第二個參數,擴展列表文件是我的第一個參數

我努力了:

for i in $1 ; do
   find . -name $2\*.$i -print>>result.txt
done

但不起作用

如評論中所述:

寫入硬編碼的文件名不是一個好主意。 給定的示例僅修復了OP問題中的給定代碼。 是的,當然,最好打電話給

x.sh y . > blabla

並從腳本本身中刪除文件名。 但是我的目的不是解決這個問題。

以下bash腳本,名為x.sh

#!/bin/bash
echo -n >result.txt                             # delete old content
while read i; do                                # read a line from file
       find $2 -name \*.$i -print>>result.txt   # for every item do a find
done <$1                                        # read from file named with first arg from cmdline  

帶有名為y的文本文件,其內容如下

txt
sh

並致電:

./x.sh y .

生成文件result.txt ,其內容為:

a.txt
b.txt
x.sh

好的,讓我們從注釋中獲得一些其他提示:如果結果字段不應從腳本的其他結果中收集任何其他內容,則可以簡化為:

#!/bin/bash
while read i; do                    # read a line from file
       find $2 -name \*.$i -print   # for every item do a find
done <$1 >result.txt                # read from file named with first arg from cmdline

就像已經提到的:可以刪除硬編碼的result.txt,並且調用可以像

./x.sh y . > result.txt

試試這個單線命令。

/ mydir替換為要搜索的文件夾。

更改作為參數傳遞給egrep命令的擴展列表:

find /mydir -type f | egrep "[.]txt|[.]xml" >> result.txt

egrep之后 ,每個擴展名應該用|分隔|

. char必須使用[.]進行轉義

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM