Florin Stingaciu
Florin Stingaciu

Reputation: 8275

Sed find,match and replace

So I have the following script (just a test)

 #!/bin/bash
 for file in *
 do
 echo $file 
 done

And I'm trying to add parenthesis around file. I'm also pretending I dont know the full name of the variable file.

  cat sc.sh | sed 's/fi*/(&)/g'
  #!/bin/bash
  (f)or (fi)le in *
  do
  echo $(fi)le
  done

So basically I'm trying to match words beginning with fi and adding parenthesis around them. What am I doing wrong? I tried a number of variations to that but it didn't work. From what I can see the command matches any f or fi and adds parenthesis around them but not the whole word. Why?

Any help would be greatly appreciated.

Upvotes: 1

Views: 425

Answers (1)

John Lawrence
John Lawrence

Reputation: 2923

Your regex fi* is looking for an f followed by 0 or more i's. You probably want something more like this:

cat tmp | sed 's/\bfi[^ ]*/(&)/g'

\bfi looks for a word boundary (i.e. the start of a word) followed by 'fi'. Then [^ ]* matches the remaining (non-space) characters in the word.

Upvotes: 1

Related Questions