0

I need to format a text file (a Fortran source code) and change some keywords from small letters to capitals or vice versa. I've made an array of possible keywords and have the following piece of the script:

 for ((i=0; i<$nwords; i++ )); do
    word=${words[$i]}
    small=${word,,}
    cap=${word^^}
    sed -i "s/$small/$cap/gI" $filein
  done

It works as it should. The problem is the following:

Suppose one of the keywords is "use", and somewhere in the test I have a word "uselog". The script changes it to "USErlog" and I want to avoid it anyhow. My idea is to put spaces in the keywords, but somehow they are automatically trimmed. I mean, I try "use " or 'use ' instead of 'use', but the result is the same.

I guess there must be a simple way to do that, like using quotes, parenthesis or similar, but so far I have not found one. Other alternatives are welcome as well.

  • Does the source code contain literal strings where the keywords could also appear (e.g. print*,"You cannot use that function for this data") but where they should not be transformed? – AdminBee Jan 26 '21 at 09:13

1 Answers1

0

with GNU sed you can use word boundry \b

Matches a word boundary; that is it matches if the character to the left is a “word” character and the character to the right is a “non-word” character, or vice-versa.

sed 's/\bword\b/newword/g' file.txt

Simply just for putting space in the keyword:

sed 's/\sword\s/ newword /g' file.txt

please note that the neword have one space at each side.

binarysta
  • 3,032