Unix/Linux Shell:按字段分析文本CVS文件分隔符

时间:2020-01-09 10:42:04  来源:igfitidea点击:

如何编写一个shell脚本来逐行解析csv文件。
然后必须逐行再次解析行。
示例输入文件如下:

example.com,username,groupname,homedir,md5password,permission,secondarygroup

如何提取每个example.com,用户名,组名,homedir,md5password,权限,secondarygroup字段,然后传递给不同的系统实用程序。如何编写shell脚本来自动执行此任务,并使用bash shell解析文本文件? 您可以使用bash while循环并读取内置命令:

  • while循环命令while语句用于重复执行命令列表。
  • read命令如果要在运行脚本时接收输入,请使用read命令。 read语句接受来自键盘或者文件的输入。
  • $IFS内部字段分隔符(IFS),用于在扩展后进行单词拆分,并使用read Builtin命令将行拆分为单词。

例子

在此示例中,使用while和read命令的组合读取逗号分隔值(CVS)文本文件。
这是一个示例file.cvs

theitroad.local,foo,bar,user1,password1,homedir1,chroot
theitroad.com,oof,rab,user2,password2,homedir,nochroot

创建一个shell脚本,如下所示:

#!/bin/bash
input="/path/to/your/input/file.cvs"
# Set "," as the field separator using $IFS 
# and read line by line using while read combo 
while IFS=',' read -r f1 f2 f3 f4 f5 f6 f7
do 
  echo "$f1 $f2 $f3 $f4 $f5 $f6 $f7"
done < "$input"

保存并关闭文件。
如下运行:

$ ./script.sh

输出示例:

theitroad.local foo bar user1 password1 homedir1 chroot
theitroad.com oof rab user2 password2 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"
done < "$input"

IFS是一个特殊的shell变量。
内部字段分隔符(IFS),用于在扩展后进行单词拆分,并使用read Builtin命令将行拆分为单词。

使用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 = "," } ; { print }' < input.cvs

在此示例中,使用from file.cvs显示域名:

awk 'BEGIN { FS = "," } ; { print  }' < file.svs

输出示例:

theitroad.local
theitroad.com

在这个最后的示例中,使用awksystem(cmd)根据需要将f1,f2和其他字段传递给其他Linux或者Unix命令以执行cmd:

awk 'BEGIN { FS = "," } ; { cmd="/path/to/useradd -d"  " " $f2; system(cmd) }' < file.svs