How to change only specific letters within a word us bash scripting

0

I have a file that contains addresses like:
0x0003ffff
0x0003ffff
0x0000ffff
0x0000ffff
0x003fffff
0x05ffffff
0x3fffffff
0x000000ff There can be 'n' number of such addresses in that file , i want the addresses changed to

0x0003FFB0
0x0003FFB0
0x0000FFB0
0x0000FFB0
0x003FFFB0
0x05FFFFB0
0x3FFFFFB0
0x000000B0 For all the 'n' addresses. What i basically want is to change the last 2 'ff's into 'B0' and the remaining 'f's into 'F' How can i do that using bash scripting?

bash
asked on Stack Overflow May 10, 2012 by Nikhilesh Sharma • edited May 10, 2012 by Nikhilesh Sharma

3 Answers

1

Use sed:

sed --in-place 's/\(0x000[0-9]\)ffff/\1FFB0/' file

Try it without the --in-place flag first to make sure it's what you want.

In case, like Nikhilesh Sharma pointed out, you might have more F's than indicated in your question, you can use the following. I'm assuming you have GNU sed. Let me know if this doesn't work and I'll give you the longer, but posix friendly, version.

sed --in-place 's/\(0x[0-9f]\{6\}\)ff/\U\1B0/' file

Here's a good tutorial to cut your teeth on sed.

answered on Stack Overflow May 10, 2012 by Tim Pote • edited May 10, 2012 by Tim Pote
0

Assuming that:

  1. your input file is called input.txt
  2. all addresses start at column 1
  3. you want to keep the first 8 characters
  4. all addresses end with ff

then this could work (at least it works for your input):

cat input.txt | cut -b1-8 | tr f F | sed s/$/B0/g
answered on Stack Overflow May 10, 2012 by redcurry
0

If you have gawk, use numeric operations instead of string operations

gawk '
  {n = strtonum($1)} 
  (n % 0x100) == 0xff {printf("0x%08X\n", n - 0x4f)}
'
answered on Stack Overflow May 10, 2012 by glenn jackman

User contributions licensed under CC BY-SA 3.0