从文本文件中剪切与模式匹配的特定单词
Cut specific words matching a pattern from a text file
我正在尝试使用 shell 脚本从匹配模式的文本文件中提取单词。例如,如果一行包含
This is a sample text to illustrate my scenario text=info id=2342
Second line to illustrate text=sample id=q2312
我希望输出像
text=info id=2342
text=sample id=q2312
有人能告诉我如何使用 cut/grep 命令实现它吗?
这个 grep -oP
应该有效:
grep -oP '\b(\w+=\w+(\s+|$))+' file
text=info id=2342
text=sample id=q2312
您可以执行以下操作:
grep -P -o 'text=\S+ id=\S+'
grep
的 -P
标志启用 perl 正则表达式。 \S+
将匹配所有非空白 space 字符,-o
仅输出匹配的部分。
假设您需要获取字段 "text" 和 "id" 值。根据需要修改正则表达式。对于 perl 正则表达式,请参阅 here 或扩展正则表达式,请参阅 man grep
使用 cut 你需要额外处理(从第一个开始剪切 = 并添加文本 =):
echo "text=$(echo "This is a sample text to illustrate my scenario text=info id=2342" | cut -d= -f2-)"
使用 sed:
echo "This is a sample text to illustrate my scenario text=info id=2342" | sed 's/.* text=/text=/'
我正在尝试使用 shell 脚本从匹配模式的文本文件中提取单词。例如,如果一行包含
This is a sample text to illustrate my scenario text=info id=2342
Second line to illustrate text=sample id=q2312
我希望输出像
text=info id=2342
text=sample id=q2312
有人能告诉我如何使用 cut/grep 命令实现它吗?
这个 grep -oP
应该有效:
grep -oP '\b(\w+=\w+(\s+|$))+' file
text=info id=2342
text=sample id=q2312
您可以执行以下操作:
grep -P -o 'text=\S+ id=\S+'
grep
的 -P
标志启用 perl 正则表达式。 \S+
将匹配所有非空白 space 字符,-o
仅输出匹配的部分。
假设您需要获取字段 "text" 和 "id" 值。根据需要修改正则表达式。对于 perl 正则表达式,请参阅 here 或扩展正则表达式,请参阅 man grep
使用 cut 你需要额外处理(从第一个开始剪切 = 并添加文本 =):
echo "text=$(echo "This is a sample text to illustrate my scenario text=info id=2342" | cut -d= -f2-)"
使用 sed:
echo "This is a sample text to illustrate my scenario text=info id=2342" | sed 's/.* text=/text=/'