bash:grep 仅符合特定条件的行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9397116/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
bash: grep only lines with certain criteria
提问by user1155413
I am trying to grep out the lines in a file where the third field matches certain criteria. I tried using grep but had no luck in filtering out by a field in the file. I have a file full of records like this:
我试图在文件中找出第三个字段与某些条件匹配的行。我尝试使用 grep 但没有运气通过文件中的字段过滤掉。我有一个充满记录的文件,如下所示:
12794357382;0;219;215
12795287063;0;220;215
12795432063;0;215;220
I need to grep only the lines where the third field is equal to 215 (in this case, only the third line)
我只需要 grep 第三个字段等于 215 的行(在这种情况下,只有第三行)
Thanks a lot in advance for your help!
非常感谢您的帮助!
回答by Ignacio Vazquez-Abrams
Put down the hammer.
放下锤子。
$ awk -F ";" ' == 215 { print while read line; do
OLF_IFS=$IFS; IFS=";"
line_array=( $line )
IFS=$OLD_IFS
test "${line_array[2]}" = 215 && echo "$line"
done < file | grep _your_pattern_
}' <<< $'12794357382;0;219;215\n12795287063;0;220;215\n12795432063;0;215;220'
12795432063;0;215;220
回答by jfg956
A solution in pure bash for the pre-processing, still needing a grep:
用于预处理的纯 bash 解决方案,仍然需要grep:
grep -E "[^;]*;[^;]*;215;.*" yourFile
回答by Kent
grep:
格雷普:
awk -F';' '==215' yourFile
in this case, awk would be easier:
在这种情况下,awk 会更容易:
cat your_file | while read line; do
if [ `echo "$line" | cut -d ";" -f 3` == "215" ]; then
# This is the line you want
fi
done
回答by Some programmer dude
How about something like this:
这样的事情怎么样:
sed -n '/^[^;]*;[^;]*;215;/p' file.txt
回答by anubhava
Here is the sed version to grep for lines where 3rd field is 215:
这是用于 grep 第三字段为 215 的行的 sed 版本:
cut -d ";" -f 3 file | paste -d ";" - file
回答by jfg956
Simplify your problem by putting the 3rd field at the beginning of the line:
通过将第三个字段放在行的开头来简化您的问题:
grep "^215;" | cut -d ";" -f 2-
then grepfor the lines matching the 3rd field and remove the 3rd field at the beginning:
然后grep对于与第三个字段匹配的行并在开头删除第三个字段:
cut -d ";" -f 3 file | paste -d ";" - file | grep "^215;" | cut -d ";" -f 2- | grep _your_pattern_
and then you can grepfor whatever you want. So the complete solution is:
然后你可以grep为任何你想要的。所以完整的解决方案是:
egrep ';215;[0-d][0-d][0-d]$' /path/to/file
Advantage: Easy to understand; drawback: many processes.
优点:易于理解;缺点:过程多。
回答by Shiplu Mokaddim
Simple egrep (=grep -E)
简单的 egrep (= grep -E)
egrep ';215;[[:digit:]]{3}$' /path/to/file
or
或者
##代码##
