![查看所有 Bash/Shell 脚本相关的常见问题解答](https://www.alaica.com/wp-content/uploads/linux-63.png)
我在一家小型 ISP(互联网服务提供商)工作,我们使用带有 bash shell 的 Linux 和类 Unix 操作系统。我想编写一个shell脚本来逐行解析csv文件。然后必须逐字段再次解析行。示例输入文件如下:
example.com,用户名,组名,homedir,md5密码,权限,辅助组
我需要提取每个 example.com、用户名、组名、homedir、md5password、permission、 secondarygroup 字段并传递给不同的系统实用程序。如何编写 shell 脚本来自动执行此任务并使用 bash shell 解析文本文件?
[请勿打印]
教程详情 | |
---|---|
难度级别 | 简单的 |
根权限 | 不 |
要求 | Bash/Ksh awk |
美东时间。阅读时间 | 3分钟 |
[/donotprint]您可以使用bash while 循环并读取内置命令:
- while 循环命令 – while 语句用于重复执行命令列表。
- 读取命令 – 如果您想在运行脚本时接收输入,请使用读取命令。read 语句接受来自键盘或文件的输入。
- $IFS – 内部字段分隔符 (IFS),用于扩展后的字拆分以及使用 read 内置命令将行拆分为字。
例子
在此示例中,使用 while 和 read 命令的组合读取逗号分隔值 (CVS) 文本文件。这是一个示例file.cvs:
example.com,foo,bar,user1,password1,homedir1,chroot example.com,oof,rab,user2,password2,homedir,nochroot
创建一个shell脚本如下:
#!/bin/bash input = "/path/to/your/input/file.cvs" # 使用 $IFS 设置“,”作为字段分隔符 # 并使用 while read 组合逐行读取 while IFS = ',' read -r f1 f2 f3 f4 f5 f6 f7 do echo " $f1 $f2 $f3 $f4 $ f5 $f6 $f7 " did < " $input "
保存并关闭文件。按如下方式运行:
$ ./script.sh
示例输出:
example.com foo bar user1 密码1 homedir1 chroot example.com oof rab 用户2 密码2 homedir nochroot
您可以根据需要将 f1、f2 和其他字段传递给其他 Linux 或 Unix 命令:
#!/bin/bash input = "/path/to/your/input/file.cvs" while IFS = ',' read -r f1 f2 f3 f4 f5 f6 f7 do / path / to / useradd -d " $f4 " " $f2 " 完成 < " $input "
IFS 是一个特殊的 shell 变量。内部字段分隔符 (IFS),用于扩展后的字拆分以及使用 read 内置命令将行拆分为字。
使用 awk 解析 CVS 文件
awk 使用名为 FS 的字段分隔符,并且不使用如上所述的 POSIX 兼容 shell 使用的名称 IFS。语法如下:
awk 'BEGIN { FS = "," } ; { do_something_here }' < input.cvs awk 'BEGIN { FS = "," } ; { do_something_here } END{ clean_up_here }' < input.cvs awk 'BEGIN { FS = "," } ; { 打印 }' <输入.cvs
在此示例中,使用 from file.cvs 显示域名:
awk 'BEGIN { FS = "," } ; { print $1 }' <文件.svs
输出示例:
example.com example.com
在最后一个示例中,使用 awk 将 f1、f2 和其他字段根据您的要求传递给其他 Linux 或 Unix 命令system(cmd)来执行 cmd:
awk 'BEGIN { FS = "," } ; { cmd="/path/to/useradd -d" $4 " " $f2; 系统(cmd) }' <文件.svs
也可以看看
- Ksh 逐行读取文件(UNIX 脚本)
- 手册页 –