Find the answer to your Linux question:
Results 1 to 3 of 3
I've a file which looks something like this: <snip from packetLog.c> printf("\ntxPackets=0x%x\n",txPackets); printf("\ntxPacketsOut=0x%x\n",txPacketsOut); printf("\ntxBytes=0x%x\n",txBytes); printf("\nOutwardtxBytes=0x%x\n",OutwardtxBytes); <snip from packetLog.c> Now i want to replace all such parameters i.e. txPackets, txPacketsOut, txBytes, ...
  1. #1
    Just Joined! amit4g's Avatar
    Join Date
    Feb 2007
    Location
    Bangalore,India
    Posts
    63

    need help: text replacement with sed

    I've a file which looks something like this:

    <snip from packetLog.c>
    printf("\ntxPackets=0x%x\n",txPackets);
    printf("\ntxPacketsOut=0x%x\n",txPacketsOut);
    printf("\ntxBytes=0x%x\n",txBytes);
    printf("\nOutwardtxBytes=0x%x\n",OutwardtxBytes);
    <snip from packetLog.c>

    Now i want to replace all such parameters i.e. txPackets, txPacketsOut, txBytes, OutwardtxBytes) etc to be renamed as
    txPacketsP1,txPacketsOutP1, txBytesP1, OutwardtxBytesP1 respectively. so i wrote a shell script using sed as

    #!/bin/bash
    sed -i s/txPackets/txPacketsP1/g packetLog.c
    sed -i s/txPacketsOut/txPacketsOutP1/g packetLog.c
    sed -i s/txBytes/txBytesP1/g packetLog.c
    sed -i s/OutwardtxBytes/OutwardtxBytesP1/g packetLog.c

    seemed simple but it doesn't work, now packetLog.c becomes:

    printf("\ntxPacketsP1=0x%x\n",txPacketsP1);
    printf("\ntxPacketsP1Out=0x%x\n",txPacketsP1Out); <-- required is txPacketsOutP1
    printf("\ntxBytesP1=0x%x\n",txBytesP1);
    printf("\nOutwardtxBytesP1P1=0x%x\n",OutwardtxBytesP1P1); <--- required is OutwardtxBytesP1

    But this is not what I've wanted, Hence please let me know how should i go about doing this.

    Regards,
    -amit

  2. #2
    Trusted Penguin Cabhan's Avatar
    Join Date
    Jan 2005
    Location
    Seattle, WA, USA
    Posts
    3,230
    So, the problem here is that "txPacketsOut" contains "txPackets". So when you do a replacement of every "txPackets", it replaces this text EVERYWHERE, not just when it is a whole "word".

    So you want to use actually match "\btxPacketsOut\b", "\btxPackets\b", etc. "\b" is a word boundary. For example:
    Code:
    alex@niamh:~$ echo "foo" | sed -re 's/\bfoo\b/hello/'
    hello
    alex@niamh:~$ echo "foos" | sed -re 's/\bfoo\b/hello/'
    foos
    You can see that it gets replacd in the first instance (because the "foo" is a word), but not in the second.
    DISTRO=Arch
    Registered Linux User #388732

  3. #3
    Just Joined! amit4g's Avatar
    Join Date
    Feb 2007
    Location
    Bangalore,India
    Posts
    63
    Thanks a ton Cabhan. It worked

Posting Permissions

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