0

How can I write a sed expression, which looks through a line to match

Id int

and change to

Id string

this will be the only content in that line (nothing other than, Id int) and should not alter other lines.

I tried with something along the lines

find . -type f -print0 | xargs -0  sed -i '' 's~^\([[:space:]]*\)"Id"[[:space:]]*"int"[:space:]]*$~\1"Id string"~g'

But the reg exp is wrong.

Thanks.

Edit:

To clarify further: There are spaces (inconsistent) before Id, between Id and int. So, needs to match [[:space:]]* , instead of tab or expressions like s/^Id int$

so the lines to match can be

   Id int
Id   int
  Id      int

It can be replaced with

Id string
Id string
Id string

means, no need to preserve the number of spaces

bsr
  • 57,282
  • 86
  • 216
  • 316

2 Answers2

0

I believe the following will do what you want:

sed 's/^Id int$/Id string'

The ^ means start of the line, and $ means end of the line, so we restrict the changes to lines which only contain Id int and not lines like I like Id int.

Update following OP clarification:

If you want to match the cases where there is varying whitespace, and preserve this whitespace then you could use:

sed 's/^\([[:space:]]*\)Id\([[:space:]]+\)int\([[:space:]]*\)$/\1Id\2string\3/'

This will preserve the whitespace before Id, between the Id and int, and after int. If you don't want to preserve the whitespace between the words or after thet last word, remove the group match parameters \2 and \3 from the sed experession.

imp25
  • 2,327
  • 16
  • 23
  • well, I have spaces before and after Id. There are spaces between Id and int. All these spaces are not consistent (means can be 1, 2,..). – bsr Nov 05 '13 at 03:45
0

Easier with awk:

awk '$2=="int"{$2="string"}1'

And potentially easier to tweak to your actual needs.

Kevin
  • 53,822
  • 15
  • 101
  • 132