1845819 Members
3829 Online
110250 Solutions
New Discussion

Re: Use grep command

 
SOLVED
Go to solution
midham
Occasional Advisor

Use grep command

Hi,

I have a file where each line contain 200 chars but some line have less than 200 chars. I want to split it by 2 files where one file contain just 200 chars and another one less than 200 chars.

Can i used grep command to solve this problem.

Thanks in advance.
6 REPLIES 6
Victor Fridyev
Honored Contributor

Re: Use grep command

Hi,

I'm not sure that that grep is the best choice, I personally in this case prefer wc

cat file | while read STRING; do
if [ $(echo $STRING|wc -c) -gt 200 ]; then
echo $STRING>>more200
else
echo $STRING >>less200
fi
done

HTH
Entities are not to be multiplied beyond necessity - RTFM
john korterman
Honored Contributor
Solution

Re: Use grep command

Hi,

awk might be helpful:

# awk 'length == 200' ./infile
# awk 'length < 200' ./infile

regards,
John K.
it would be nice if you always got a second chance
Leif Halvarsson_2
Honored Contributor

Re: Use grep command

Hi

I would prefer awk for this problem, but another useful tool is wc

while read line
do
if [ $( echo $line |wc -c) -eq 200
then
echo $line >>file1
else
echo $line >>file2
done
Alessandro Pilati
Esteemed Contributor

Re: Use grep command

Here it is in a single line:

awk ' { if ( length==200 ) print $0 > "200.txt"; else print $0 > "less200.txt";} ' textfile

Regards,
Alex
if you don't try, you'll never know if you are able to
midham
Occasional Advisor

Re: Use grep command

Thanks a lot. All of you are very excellent.
midham
Occasional Advisor

Re: Use grep command

For extract or manipulate the data from the text file, it is better use awk command rather than grep.