Results 1 to 3 of 3

Thread: Sed and Awk

  1. #1
    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

    anyone...anyone...

    Thomas

  2. #2
    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

    BRGs

  3. #3
    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.

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

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •