通过bash读取文件夹中的任何.txt文件

通过bash读取文件夹中的任何.txt文件,bash,shell,Bash,Shell,我的想法是,我想读取特定文件夹中的任何.txt文件并做一些事情。所以我尝试了以下代码: #!/bin/bash #Read the file line by line while read line do if [ $i -ne 0 ]; then #do something... fi done < "*.txt" echo "Finished!" #/bin/bash #逐行读取文件 读行时 做 如果[$i-ne 0];然后 #做点什么。。。 fi 完成

我的想法是,我想读取特定文件夹中的任何.txt文件并做一些事情。所以我尝试了以下代码:

#!/bin/bash
#Read the file line by line
while read line
do
    if [ $i -ne 0 ]; then
       #do something...
    fi
done < "*.txt"
echo "Finished!"
#/bin/bash
#逐行读取文件
读行时
做
如果[$i-ne 0];然后
#做点什么。。。
fi
完成<“*.txt”
回声“完成!”
我想你现在明白我的意思了。谢谢你的建议


完成一些操作后,我想将文件移动到另一个文件夹。

不确定您的
if
语句中有什么
$I
。。但您可以像这样逐行读取dir中的所有.txt文件:

while read line; do
    # your code here, eg
    echo "$line"
done < <(cat *.txt)
读行时
;做
#你的代码在这里
回音“$line”

完成<为了避免不必要地使用
cat
,您可以使用
for
循环:

for file in *.txt
do 
    while read line
    do  
        # whatever
        mv -i "$file" /some/other/place
    done < "$file"
done
用于*.txt中的文件
做
读行时
做
#随便
mv-i“$file”/some/other/place
完成<“$file”
完成
这将单独处理每个文件,以便您可以单独对每个文件执行操作。如果要将所有文件移动到同一位置,可以在循环之外执行此操作:

for file in *.txt
do
    while read line
    do  
        # whatever        
    done < "$file"
done
mv -i *.txt /some/other/place
用于*.txt中的文件
做
读行时
做
#随便
完成<“$file”
完成
mv-i*.txt/some/other/place

正如评论中所建议的,我已将
-I
开关添加到
mv
,在覆盖文件之前会提示。这可能是一个好主意,尤其是在扩展
*
通配符时。如果您不想被提示,您可以改为使用
-n
开关,该开关不会覆盖任何文件。

@TomFenech好吧,在
done<“*.txt”
中有一些问题。但现在根据Josh的回答解决了。@TrueBlue没问题。在做了一些工作之后,我想将文件移动到另一个文件夹。我可以在同一个bash shell上做吗?@TrueBlue是的,你可以,我已经把它添加到我的答案中了。如果您有更多信息要添加,您应该编辑您的问题。两个
mv
安全命令上都应该有
-i
标志。问题已经编辑,因此此方法不再有效。
for file in *.txt
do
    while read line
    do  
        # whatever        
    done < "$file"
done
mv -i *.txt /some/other/place