简体   繁体   English

如何从文件的grep中拆分行?

[英]How to split lines from a grep on a file?

Given Employee.txt,给定 Employee.txt,

PD:198801221:Jason:Jason@gmail.com
PU:19941029:Tan:tan@gmail.com
PS:19960601:May:may@gmail.com

and a form,和一个表格,

echo -n "Enter BirthDate:";read bdate
grep "$bdate" Employee.txt
echo "Employee name (auto display):"
echo "Employee email (auto display):"

which takes an employee birth date and displays the name and email based on the input file.它获取员工的出生日期并根据输入文件显示姓名和电子邮件。

For example, if I input in the BirthDate as 19941029 , the result I get from the file is PU:19941029:Tan:tan@gmail.com例如,如果我在 BirthDate 中输入19941029 ,我从文件中得到的结果是PU:19941029:Tan:tan@gmail.com

The above script displays the entire line.上面的脚本显示了整行。

How can I separate the line into the auto display name and email fields?如何将行分成自动显示名称和电子邮件字段?

You can use IFS to read the input into 4 variables您可以使用 IFS 将输入读入 4 个变量

echo -n "Enter BirthDate:";read bdate

match=$(grep "$bdate" Employee.txt)
IFS=':' read -r first second third fourth <<<$match


echo "Employee name (auto display):" $third
echo "Employee email (auto display):" $fourth

References参考

https://bash.cyberciti.biz/guide/$IFS https://bash.cyberciti.biz/guide/$IFS

https://unix.stackexchange.com/questions/209123/understanding-ifs-read-r-line https://unix.stackexchange.com/questions/209123/understanding-ifs-read-r-line

You can pipe the grep output through cut and pick up the fields you want.您可以通过cut管道输出 grep 并选择所需的字段。

#!/usr/bin/env bash
set -eu

echo -n "Enter BirthDate: "
read -r bdate

found=$(grep "$bdate" Employee.txt)
name=$(echo "$found" | cut -d: -f 3)
email=$(echo "$found" | cut -d: -f 4)

echo "Employee name (auto display): $name"
echo "Employee email (auto display): $email"

This is fairly simplistic and breaks if your fields contain separator characters (colons in this case).如果您的字段包含分隔符(在这种情况下为冒号),则这相当简单并且会中断。 In that case you should get a CSV reader.在这种情况下,您应该获得一个 CSV 阅读器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM