Bash: grep only lines with specific criteria

I am trying to cross out lines in a file where the third field matches certain criteria. I tried using grep but could not filter the field in the file. I have a file full of such entries:

12794357382;0;219;215 12795287063;0;220;215 12795432063;0;215;220 

I need grep only lines where the third field is 215 (in this case only the third line)

Thanks for your help!

+4
source share
7 answers

Put down the hammer.

 $ awk -F ";" '$3 == 215 { print $0 }' <<< $'12794357382;0;219;215\n12795287063;0;220;215\n12795432063;0;215;220' 12795432063;0;215;220 
+5
source

Grep:

 grep -E "[^;]*;[^;]*;215;.*" yourFile 

awk will be easier in this case:

 awk -F';' '$3==215' yourFile 
+2
source

A solution in pure bash for preprocessing that still needs grep :

 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_ 
+2
source

Simple egrep (= grep -E )

 egrep ';215;[0-d][0-d][0-d]$' /path/to/file 

or

 egrep ';215;[[:digit:]]{3}$' /path/to/file 
+1
source

How about something like this:

 cat your_file | while read line; do if [ `echo "$line" | cut -d ";" -f 3` == "215" ]; then # This is the line you want fi done 
+1
source

Here is the sed version of grep for strings where the 3rd field is 215:

 sed -n '/^[^;]*;[^;]*;215;/p' file.txt 
+1
source

Simplify the problem by putting a third field at the beginning of the line:

 cut -d ";" -f 3 file | paste -d ";" - file 

then grep for the lines corresponding to the 3rd field, and remove the third field at the beginning:

 grep "^215;" | cut -d ";" -f 2- 

and then you can grep for whatever you want. So the complete solution:

 cut -d ";" -f 3 file | paste -d ";" - file | grep "^215;" | cut -d ";" -f 2- | grep _your_pattern_ 

Advantage : easy to understand; drawback : many processes.

+1
source

Source: https://habr.com/ru/post/1397833/


All Articles