我怎么能一次 grep 两次?

Jim*_*Jim 8 shell grep bash shell-script

有没有办法避免grep在文件中执行两次并一次性填充变量?文件很小,所以没什么大不了的,我只是想知道我是否可以一次性完成

FIRST_NAME=$(grep "$customer_id" customer-info|cut -f5 -d,)
LAST_NAME=$(grep "$customer_id" customer-info|cut -f6 -d,)
Run Code Online (Sandbox Code Playgroud)

Olo*_*rin 13

您可以使用 shell 字符串替换 grep 一次并拆分两次:

NAME=$(grep "$customer_id" customer-info | cut -f5,6 -d,)
FIRST_NAME=${NAME%,*}
LAST_NAME=${NAME#*,}
Run Code Online (Sandbox Code Playgroud)

或者,使用 bash,使用进程替换:

IFS=, read FIRST_NAME LAST_NAME < <(grep "$customer_id" customer-info | cut -f5,6 -d,)
Run Code Online (Sandbox Code Playgroud)

read将拆分输入IFS并将第一个值分配给FIRST_NAME,其余分配给LAST_NAME。使用进程替换和重定向< <(...)允许您grep ... | cut ...read不使用子shell 的情况下传递 to 的输出。