linux 系统中的 for 循环结构

1、基本结构

#!/bin/bash   ## 声明脚本解释器
for 变量 in 可迭代对象
do
循环体
done

 

2、简单实例

[root@linuxprobe test3]# for i in 1 10 100 500;do echo $i;done  ## 可以直接在命令行中使用,变量前需加 $ 符号。
1
10
100
500

 

[root@linuxprobe test3]# ls
[root@linuxprobe test3]# for i in a b c x y z;do mkdir $i;done
[root@linuxprobe test3]# ls
a  b  c  x  y  z

 

3、可迭代对象可以放在文件中

复制代码
[root@linuxprobe test3]# cat test.txt
abc
www
eee
ttt
[root@linuxprobe test3]# for i in `cat test.txt`;do touch $i;done  ## 注意是反引号;反引号的部分可以使用 $(命令)代替
[root@linuxprobe test3]# ls
abc  eee  test.txt  ttt  www

[root@linuxprobe test3]# for i in $(cat test.txt);do rm -f $i;done  ## 删除刚才创建的内容
[root@linuxprobe test3]# ls
test.txt

 
复制代码

 

4、实例

  创建测试数据

复制代码
[root@linuxprobe test3]# cat test.txt ## 测试数据
2 3 4
5 a 7
3 2 b
2 4 9
3 5 b
3 9 c
3 3 4
2 4 a
4 8 5
[root@linuxprobe test3]# cat a.txt  ## 计划从test.txt文件中提取所有包含a、b、c的行,
a
b
c
[root@linuxprobe test3]# for i in `cat a.txt`;do grep "$i" test.txt >> result.txt;done ## 利用for循环结构,逐个匹配字符,追加至结果文件
[root@linuxprobe test3]# cat result.txt
5 a 7
2 4 a
3 2 b
3 5 b
3 9 c
复制代码

 

posted @   小鲨鱼2018  阅读(836)  评论(0编辑  收藏  举报
编辑推荐:
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
点击右上角即可分享
微信分享提示