bash - 更好的 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
谢谢
解决方案
我以前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
推荐阅读
- sql - 使 SQL SERVER 按特定顺序评估子句
- javascript - 为什么我们不需要绑定这个函数?
- django - django如何为postgresql数据库中现有的多对多表定义模型
- javascript - w3schools 选项卡 - 所有选项卡
- javascript - 如何模拟“焦点”和“打字”事件
- function - 如何在不使用类概念的情况下将用户的输入从一个函数输入到另一个函数
- javascript - 是否可以将 HTML 元素及其所有值添加到 localStorage?
- visual-studio-2017 - 单步执行 Linq 查询时打开浏览器窗口 - “找不到源”
- javascript - 使用javascript更改json结果的键和值
- charts - 谷歌图表 - 如何从条形图中删除注释?