Results 1 to 6 of 6
Hi ,
I have one file as "Names.txt" . It contains,
animal=cow
animal-1=bull
bird=parrot
I need to search the word='animal' in the file Names.txt and creat the new file with ...
- 09-30-2011 #1Just Joined!
- Join Date
- Sep 2011
- Posts
- 0
grep exact word from the file and awk the string
Hi ,
I have one file as "Names.txt" . It contains,
animal=cow
animal-1=bull
bird=parrot
I need to search the word='animal' in the file Names.txt and creat the new file with the detail "cow". like this i ll create the new file using do while loop.
I have two issues for doing this
1) grep the exact word.. If i grep the word animal, both animal and animal1 one also coming for the condition. That issue solved. i used "animal=".
2) i am using the awk command to seperate the word "cow"
awk -F "=" '{print $2}' <file name>. Here i cannot avoid the issue mentioned in the point 1. its coming again.
Could you please help me to solve this.
How to take excact word using awk command.???
Thanks in advance..
Chelladurai.
- 09-30-2011 #2Linux Guru
- Join Date
- May 2011
- Posts
- 1,813
man awk
Look for the section on Regular Expressions, and specifically:
Look at scripts in /etc/init.d/ for some good examples.Code:^ matches the beginning of a string. $ matches the end of a string.
- 10-01-2011 #3Just Joined!
- Join Date
- Jun 2006
- Location
- Bangalore, India
- Posts
- 28
Try the following:
grep 'animal=' Names.txt | cut -d= -f2 > output.txt
It extracts only the detail of the animal coming after animal=.
- 10-01-2011 #4Linux Engineer
- Join Date
- Feb 2005
- Posts
- 1,044
You can do it all with awk as follows:
awk "-F=" '/^animal=/ {print $2}' Names.txt
Or prefix your awk version with the output from the grep you've done:
grep '^animal=' Names.txt | awk "-F=" '{print $2}'
- 10-02-2011 #5
For 'problems' like this you can use bash buildins like parameter substitution
Or, depending on the complexity of your source file, even simpler:Code:VAR=`grep '^animal=' Names.txt` echo ${VAR##*=}
Code:. Names.txt echo $animal
Can't tell an OS by it's GUI
- 10-02-2011 #6Just Joined!
- Join Date
- Sep 2007
- Posts
- 51
Extract text info
I was just thinking that if the file had animal=cow, animal=parrot and any other type of variation, then the program would provide false results based on the comments below, with this integration of cow using && statements, we are not limited by beginning or end characters and it functions in the same way as the previous program. Basically it would provide you with more control if more strings matched the "animal=" statements. The statement below is from the "scm" user.Code:awk -F"=" '/animal/ && /cow/ {print $2}' Names.txt
TCode:awk -F"=" '/^animal=/ {print $2}' Names.txtLast edited by tdsan; 10-02-2011 at 06:36 PM.


Reply With Quote
