Databases
cancel
Showing results for 
Search instead for 
Did you mean: 

extracting records from a data file

SOLVED
Go to solution
Joe Robinson_2
Super Advisor

extracting records from a data file

I'm trying to pull a number of records that contain 'X' as the seventh character of the string. I've tried using wild cards (??????X) in a grep statement, as well as [A-Z]....X, but am looking for a simpler, more direct way that I can use in the future as well.

Along with that, I'm curious if there would be a way to direct records that don't have 'X' in them to another file...if the 2 files record count adds up to the original, I'm in like Flynn.

Thanks,
Joe Robinson
8 REPLIES
Jeff Machols
Esteemed Contributor

Re: extracting records from a data file

You already have the best way to extract them grep ??????X

to get the opposite, all you have to do is grep -v ??????X
Joe Robinson_2
Super Advisor

Re: extracting records from a data file

Not sure why that syntax won't work here...that was the first two things I thought of.
Curtis Larson_1
Valued Contributor

Re: extracting records from a data file

could always try

sed '/[.]\{6\}X/p'

and those without a X at the 7th character:

sed '/[.]\{6\}X/d'

Jeff Machols
Esteemed Contributor

Re: extracting records from a data file

you may need to anchor the grep by doing this

grep "^??????X" file
grep -v "^??????X" file
Jeff Machols
Esteemed Contributor

Re: extracting records from a data file

This will work also

cat file | cut -c 7 | grep X
cat file | cut -c 7 | grep -v X
Curtis Larson_1
Valued Contributor
Solution

Re: extracting records from a data file

and with grep

grep '.\{6\}X'
Jeff Machols
Esteemed Contributor

Re: extracting records from a data file

One thing you will want to add to Curtis' is

grep '^.\{6\}X' file

otherwise you will get it if X is the 8th, 9th, etc

the ^ will anchor it to the begining of the line
Curtis Larson_1
Valued Contributor

Re: extracting records from a data file

and with awk

awk '/^......X/ {print $0 >> "linesWithX";next} {print $0 >> "linesWithoutX";}'