Question

Need shell script to filter the data in a file based on certain condition.

Asked by: Sharath_123

Hi all,
I have text file on unix server in which the fields are seperated by any delimeter like pipe or comma etc. My question is i want to extract those records only which satisfies certain condition.
For eample if the file contains follwoing records
A| ABC|123|0093
B|CDE|233|0987
C|ABC|344|2345
my requirement is I want the count of the records where the second field is "ABC" and those records.

Here I have to pass the field number and field value dynamically to the script or as parameters.

Thanks in advance,
Sharath

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2006-09-26 at 03:31:16ID22002729
Tags

shell

,

script

,

file

,

filter

Topic

Unix Systems Programming

Participating Experts
3
Points
250
Comments
19

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. Can't log on with CDE
    I'm having a bizarre problem. I have a Sun Blade 100. When I log on as root, it goes into CDE with no problems. But when I create a new userID, and enter the name and password via the login dialog (dtlogin), it shows the hourglass and then goes right back to the login dial...
  2. NIS login, CDE hang
    When my nis client logins to using nis server information, it successfully login to the CDE welcome screen. But then, it hangs with no response. What should probably be the problem?
  3. CDE logout from commandline
    Is it possible to logout/exit from Common Desktop Envirnment (CDE) session from command line, i.e. shell scripts? That is: I would like to write shell script which closes CDE session and returns to Login window. Is it possible? If yes, how? thanks in advance.
  4. CDE does not allow root to login.
    Hello, When I try to login to the system as root through CDE , the login screen reappears without displaying any error message. CDE does not allow me to login to the system as root , but I can login as different user. What could be the reason ?? Thanks samy
  5. Delimeter Check
    I need help with this: Write a class method named 'DelimMatch' and a method main that will test it The method 'match' will take a String that may contain any number of parentheses, brackets, or braces as a parameter and return true if the parentheses, brackets, or braces ar...

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: ahoffmannPosted on 2006-09-26 at 06:03:38ID: 17600709

awk -F'|' '($2=="ABC"){print}' file

Note that this does not match *your* line A

> .. I have to pass the field number and field value dynamically to the script or as parameters
# assuming following in a script where $par contains your pattern
awk -F'|' '($2=="'$par'"){print}' file

 

by: TintinPosted on 2006-09-26 at 14:49:52ID: 17605828

non awk solution

#!/bin/sh
field=$1
value=$2

cut -f$field /some/file | grep -c $value

 

by: Sharath_123Posted on 2006-09-27 at 01:09:38ID: 17608298

Hi Tintin,
you solution will give the number of records which satisfies the condition.
But it won't give me those records. I want the records also.

 

by: TintinPosted on 2006-09-27 at 01:21:05ID: 17608330

#!/bin/sh
field=$1
value=$2

count=`cut -f$field /some/file | grep -c $value`
line=`cut -f$field /some/file | grep  $value`
echo "$line - $count"

 

by: Sharath_123Posted on 2006-09-27 at 02:13:31ID: 17608567

Hi Tintin,

My file has a delimeter like pipe or comma to seperate fields. You are not taking care of that. Because of that its not cutting the exact field from the file.

For example:
My file is test.txt whith the data as
a|bcd|cde|123  
c|bcd|abc|    
||bcd|swd      

cut -f2 "test.txt" | grep  "bcd" command is giving output as
a|bcd|cde|123
c|bcd|abc|    
||bcd|swd    

It should not give the 3rd record in which the "bcd" is occuring in 3rd column.

 

by: TintinPosted on 2006-09-27 at 03:24:00ID: 17608833

Whoops, forgot the -d flag to cut

cut -f2 -d'|' ......

 

by: Sharath_123Posted on 2006-09-27 at 04:23:50ID: 17609157

But stil ther ia some problem with your commands.
It won't give the complete record.

try to execute the your command
line=`cut -d'|' -f$field /some/file | grep  $value`
you are cutting a particular field from the file and searching for the value.
The input to the grep is the column only. How can you get the complete record?

 

by: Sharath_123Posted on 2006-09-27 at 04:29:22ID: 17609179

I have tried with the folloing command.

cut -f2 -d "|" test.txt | sort | uniq -c

The output of this command is
1
2 bcd

This will give the number of records and the field value. For number of records, this is fine.
But the problem is it wont displays those records.

 

by: HamdyHassanPosted on 2006-09-27 at 07:38:40ID: 17610647

you need a trick like below  ( add magic field at start as extra field, grep , then cut it out )



$ cat x1.txt
A|ABC|YZQ|0093
B|CDE|233|0987
C|ABC|656|0001
C|AXC|344|2345
C|AFC|ABC|8982
C|ABC|551|0002

$ cat x2.ksh
#!/bin/ksh

P1=$1

if [ "${2}HH" == "HH" ]; then
  P2=1
else
  P2=$2
fi

cut -f$P2 -d"|" x1.txt  | sed -e "s/$/|/" > x1_extra.txt
paste  x1_extra.txt x1.txt | sed -e "s/ //" >  x1_total.txt
grep "^${P1}|" x1_total.txt  | cut -f2- -d"|"
echo Count of ${P1} at field ${P2} is `grep "^${P1}|" x1_total.txt|wc -l`


$ x2.ksh ABC 2
A|ABC|YZQ|0093
C|ABC|656|0001
C|ABC|551|0002
Count of ABC at field 2 is 3

$  x2.ksh AXC 2
C|AXC|344|2345
Count of AXC at field 2 is 1

$ x2.ksh ABC 3
C|AFC|ABC|8982
Count of ABC at field 3 is 1

 

by: TintinPosted on 2006-09-28 at 03:15:10ID: 17617535

I see what you want now (borrowing from ahoffmans's suggestion).

#!/bin/sh
FILE=/some/file.txt

field=$1
value=$2

awk -F'|' '($"'$field'"=="'$value'"){print}' $FILE
count=`cut -f$field $FILE | grep -c $value`
echo "Total matches for $value: $count"

 

by: Sharath_123Posted on 2006-09-28 at 04:40:21ID: 17618191

Hi Tintin,
I am getting desired result with your code. One more concern is can we parameterise the delimeter in the awk also? ( we can parametrise the delimeter in the cut command)
Because my files are some times comma delimeted and some times pipe delimeted.

Hi HamdyHassan,
I have not check your code. I will check and let you know whether it is working fine or not.

regards,
Sharath

 

by: HamdyHassanPosted on 2006-09-28 at 06:41:20ID: 17619101

-----  some times comma delimeted and some times pipe delimeted
Yes you can do that

instead of -d"|"  
you use  -d$MyDel

make sure you check $3 as I did for $2, may be you can use default "|" in case $3 is empty
if [ "${2}HH" == "HH" ]; then
  P2=1
else
  P2=$2
fi

also when you can at command prompt, you need to put  " "  around |  otherwise shell consider it as pipline
$ x2.ksh ABC 2 "|"

 

by: TintinPosted on 2006-09-28 at 14:28:52ID: 17623133

#!/bin/sh
FILE=/some/file.txt

if [ $# -ne 3 ]
then
    echo "USAGE: $0 [field] [value] [delimiter]"
    exit 1
fi

field=$1
value=$2
delimiter=$3

awk -F"$delimiter" '($"'$field'"=="'$value'"){print}' $FILE
count=`cut -f$field $FILE | grep -c $value`
echo "Total matches for $value: $count"

 

by: ahoffmannPosted on 2006-10-02 at 01:47:52ID: 17641647

hmm, you can write millions of lines of error prone code in any language you can imagine ...
What is the problem with my simple, understandable awk suggestion?

 

by: Sharath_123Posted on 2006-10-03 at 21:15:01ID: 17656875

Hi Tintin,
your script is working fine. Can you elobarate it to search for records with null string in certain column. till now we displayed records with "ABC" at field num. 2, can't we display records with " " ( null value) at field num.2?

 

by: TintinPosted on 2006-10-04 at 02:41:51ID: 17657937

Be careful using the word null, as it often mistakingly gets used to mean empty or blank value.  In your case, do you mean blank value?

 

by: ahoffmannPosted on 2006-10-04 at 02:55:05ID: 17657994

> can't we display records with " "
assuming you mean a string which only consist of any number of spaces:
awk -F'|' '($2~/^ *$/){print}' file

Tintin, you know: "blank value" is ambigiuos too ;-)

 

by: Sharath_123Posted on 2006-10-04 at 05:58:20ID: 17658927

Thanks all of you for overhelming response.

 

by: HamdyHassanPosted on 2006-10-04 at 08:33:59ID: 17660179


>>>> Hi HamdyHassan,
>>>>> I have not check your code. I will check and let you know whether it is working fine or not.

Did you check my code?  
This is unfair.

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...