linux shell中for循环结构
1、循环数字
root@PC1:/home/test# ls root@PC1:/home/test# for((i = 1; i <= 5; i++)); do echo $i; done 1 2 3 4 5
2、
root@PC1:/home/test# ls root@PC1:/home/test# for i in $(seq 5); do echo $i; done 1 2 3 4 5
3、
root@PC1:/home/test# ls root@PC1:/home/test# var="1 2 3 4 5" root@PC1:/home/test# for i in $var; do echo $i; done 1 2 3 4 5
4、
root@PC1:/home/test# ls root@PC1:/home/test# awk 'BEGIN{for(i = 1; i <= 5; i++) print i}' 1 2 3 4 5
5、
root@PC1:/home/test# ls a.txt root@PC1:/home/test# cat a.txt 2 4 1 5 8 3 1 4 6 5 7 9 8 6 3 6 2 7 3 9 root@PC1:/home/test# for i in $(head -n 1 a.txt); do echo $i; done ## 按照第一行进行循环 2 4 1 5 8
6、
root@PC1:/home/test# ls a.txt root@PC1:/home/test# cat a.txt 2 4 1 5 8 3 1 4 6 5 7 9 8 6 3 6 2 7 3 9 root@PC1:/home/test# for i in $(head -n 2 a.txt); do echo $i; done ## 按照a.txt的前两行进行循环 2 4 1 5 8 3 1 4 6 5
7、
root@PC1:/home/test# ls a.txt root@PC1:/home/test# cat a.txt 2 4 1 5 8 3 1 4 6 5 7 9 8 6 3 6 2 7 3 9 root@PC1:/home/test# for i in $(awk '{print $1}' a.txt); do echo $i; done ## 按照第一列进行循环 2 3 7 6
8、
root@PC1:/home/test# ls a.txt root@PC1:/home/test# cat a.txt 2 4 1 5 8 3 1 4 6 5 7 9 8 6 3 6 2 7 3 9 root@PC1:/home/test# for i in $(awk '{print $1, $2}' a.txt); do echo $i; done ## 按照前两列进行循环 2 4 3 1 7 9 6 2
9、
root@PC1:/home/test# ls root@PC1:/home/test# for i in {1..5}; do echo $i; done 1 2 3 4 5
10、
root@PC1:/home/test# ls test1.txt test2.txt test3.txt test4.txt root@PC1:/home/test# for i in $(ls); do echo $i; done test1.txt test2.txt test3.txt test4.txt
11、
root@PC1:/home/test# ls test1.csv test1.txt test2.csv test2.txt test3.csv test3.txt test4.csv test4.txt root@PC1:/home/test# for i in $(ls *.csv); do echo $i; done ## 对指定文件类型进行循环 test1.csv test2.csv test3.csv test4.csv
12、
root@PC1:/home/test# ls root@PC1:/home/test# for i in a b c d; do echo $i; done a b c d
13、
root@PC1:/home/test# ls root@PC1:/home/test# var="x y z a b" root@PC1:/home/test# for i in $var; do echo $i; done x y z a b
14、
root@PC1:/home/test# ls a.txt root@PC1:/home/test# cat a.txt 2_4_1_5_8 3_1_4_6_5 7_9_8_6_3 6_2_7_3_9 root@PC1:/home/test# for i in $(cat a.txt); do a=$(echo $i | cut -d "_" -f 1); b=$(echo $i | cut -d "_" -f 2); echo $(expr $a + $b); done 6 4 16 8
分类:
linux shell
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律