If this is your first visit, be sure to check out the FAQ by clicking the link above. You may have to register before you can post: click the register link above to proceed. To start viewing messages, select the forum that you want to visit from the selection below.

Go Back  dBforums > Data Access, Manipulation & Batch Languages > Unix Shell Scripts > Sed and Awk

LinkBack Thread Tools Search this Thread Display Modes
  #1 (permalink)  
Registered User
Join Date: Jan 2004
Posts: 1
Sed and Awk

I thought this was going to be a simple thing but I am lost somewhere. I am hoping someone can lead me in the right direction.

I have a text file that has a list of numbers and names.

I wanted a sed/awk script that looked for a first instance of a name, then replaced it, then gave me the number.

So I used
grep OPEN file.txt | sed -n '1p;' | awk -F: '{ print $1 }'

That worked but it does not save to the file.txt. So I wanted to get rid of the grep and be able to save the result to the file.txt


Reply With Quote
  #2 (permalink)  
Registered User
Join Date: Jan 2004
Posts: 15
Please provide a sample of the contents in the file "file.txt" and also what you would like to be replaced and a solution shall be found

Reply With Quote
  #3 (permalink)  
Join Date: Jun 2002
Location: UK
Posts: 525
Re: Sed and Awk

Originally posted by wantabescripter
So I used
grep OPEN file.txt | sed -n '1p;' | awk -F: '{ print $1 }'
You need to redirect your output somewhere to save it...

grep OPEN file.txt | sed -n '1p;' | awk -F: '{ print $1 }' > newFile

There are a lot of unnecessary pipes in your command, you could actually do the whole lot in sed or awk.

I can guess the awk solution from what you have posted...

awk -F":" '/OPEN/ {print $1; exit}' yourFile > newFile

And the sed solution will be something like this...

sed -n '/OPEN/{x;/1stValueIsFound/{;x;q;}
s/^.*/1stValueIsFound/;x;s/:.*//;p;}' yourFile > newFile

I prefer the awk because it it is far easier to read and you can tell it to exit once a match has been found.

For sed, you have to keep a value in the holdspace to check against to see if the match has been found ('1stValueIsFound'). You have to keep reading the file unfortunately.


Last edited by Damian Ibbotson; 01-28-04 at 06:03.
Reply With Quote

Thread Tools Search this Thread
Search this Thread:

Advanced Search
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On