How to use shell to iterate through the content of files?
Common methods for iterating over file contents using Shell involve using a loop structure, which can be combined with keywords like for and while for iteration operations. Below are some example codes:
- for
Example: in order to
#!/bin/bash
# 遍历当前目录下所有文件
for file in *
do
# 判断是否是文件
if [ -f "$file" ]
then
# 输出文件名
echo "文件名: $file"
# 逐行读取文件内容
while IFS= read -r line
do
echo "$line"
done < "$file"
echo "---------------------"
fi
done
- during
#!/bin/bash
# 获取目录下所有文件
files=$(find . -type f)
# 遍历文件列表
for file in $files
do
# 输出文件名
echo "文件名: $file"
# 逐行读取文件内容
while IFS= read -r line
do
echo "$line"
done < "$file"
echo "---------------------"
done
The above code example simply iterates through and outputs the file contents, you can make corresponding modifications and changes based on your specific needs.