- 循环处理数据效果:
- marvin@marvin-pc:~$ cat /etc/passwd | grep marvin
marvin:x:1000:1000:marvin,,,:/home/marvin:/bin/bash
marvin@marvin-pc:~$ ifs=$IFS
marvin@marvin-pc:~$ IFS=:
marvin@marvin-pc:~$ for haha in $(cat /etc/passwd | grep marvin)
> do
> echo "this is $haha"
> done
this is marvin
this is x
this is 1000
this is 1000
this is marvin,,,
this is /home/marvin
this is /bin/bash - 嵌套循环处理文件数据:
- #!/bin/bash
#_*_coding:utf-8_*_
#写个程序拆分/etc/passwd文件中的数据
IFS_old=$IFS
IFS=$'\n'
for split_out in $(cat /etc/passwd)
do
echo "文件中的数据 $split_out"
IFS=:
for split_in in $split_out
do
echo " $split_in"
done
done
IFS=$IFS_old - 查找可执行文件
- #!/bin/bash
#_*_coding: utf-8_*_
#查找可执行的文件
IFS_old=$IFS
IFS=:
for folder in $PATH
do
echo "$folder:"
for file in $folder/*
do
if [ -x $file ]
then
echo " $file"
fi
done
done - 一次性创建多个系统用户
- #!/bin/bash
#_*_coding: utf-8_*_
#通过文件一次性创建多个账号
input="users.csv"
while IFS=',' read -r userid name
do
echo "新增用户:$userid"
useradd -c "$name" -m $userid
done < "$input" - 读取.csv文件,创建insert语句
- csv文件内容如下:
- marvin@marvin-pc:~/hylan$ cat members.csv
Blum,Richard,123 Main St.,Chicago,IL,60601
Blum,Barbara,123 Main St.,Chicago,IL,60601
Bresnahan,Christine,456 Oak Ave,Columbus,OH,43201
Bresnahan,Timothy,456 Oak Ave,Columbus,OH,43201 - marvin@marvin-pc:~/hylan$ cat sql_test
#!/bin/bash
outfile='members.sql'
IFS=','
while read lname fname address city state zip
do
cat >> $outfile << EOF
insert into members(lname,fname,address,city,state,zip) values
('$lname','$fname','$address','$city','$state','$zip');
EOF
done - 执行脚本:marvin@marvin-pc:~/hylan$ ./sql_test < members.csv
- 执行结果:marvin@marvin-pc:~/hylan$ cat members.sql
insert into members(lname,fname,address,city,state,zip) values
('Blum','Richard','123 Main St.','Chicago','IL','60601');
insert into members(lname,fname,address,city,state,zip) values
('Blum','Barbara','123 Main St.','Chicago','IL','60601');
insert into members(lname,fname,address,city,state,zip) values
('Bresnahan','Christine','456 Oak Ave','Columbus','OH','43201');
insert into members(lname,fname,address,city,state,zip) values
('Bresnahan','Timothy','456 Oak Ave','Columbus','OH','43201');
insert into members(lname,fname,address,city,state,zip) values
('','','','','','');
注意最后多了一行空值。可能需要手动处理一下。之所以会产生这条空行,是因为members.csv文件我不是用vim创建的文件,手工打开的编辑器,误留了空行(比较容易无意中留空行),如果是用vim编辑器创建的文件(不容易误留空行),没有放空行就不会出现这种空行。
hylan:shell脚本鸡肋--结构化命令(续)
最新推荐文章于 2021-05-12 08:41:07 发布