首页 > 解决方案 > 更好的 grep 搜索文件

问题描述

我在 bash 中有一个简单的脚本,它使用 grep 在文件中搜索。

我想做与下面相同的事情,但我不喜欢使用 2 个临时文件,有更好的方法吗?

    #! /bin/bash

FILE="text.txt"

rm /tmp/temp*
temp_file1=$(mktemp /tmp/temp1)
temp_file2=$(mktemp /tmp/temp2)

cp $FILE $temp_file1

for string in $@
do
grep -i "$string" $temp_file1 > $temp_file2
mv $temp_file2 $temp_file1
done

cat $temp_file1

谢谢

标签: bashgrep

解决方案


我以前awk不是为了提高性能,而是因为它更适合您的需求(在同一行搜索多个模式而不考虑顺序)

my_script.sh :

search=${@:2}
awk -v search="$search" 'BEGIN{nb_patterns=split(search, a)}{p=1;for(i=1;i<=nb_patterns;i++){if(!(tolower($0)~tolower(a[i]))){p=0}}}p' $1

test.txt 示例:

hello world
world hello
hello
world
enzjlgz

用法 :

sh test.sh test.txt HeLlo WorLd

结果 :

hello world
world hello

推荐阅读