0

I do not want to replace just any letters with words. I only want to replace letters that are stand alone with exact case sensitive matches.

I have a file that looks like this:

file>-string pile stage one on one/a>b
system > use while one is one stage/sump/f
get sole--> one by one dir/sub/main/c >b
multi string return one by one sub//c static a
ect...
ect...

I want to replace the letter that are not part of word.

a=ASTRING
b=BSTRING
c=CSTRING
f=FSTRING

The desired output would look like:

file>-string pile stage one on one/ASTRING>BSTRING
system > use while one is one stage/sump/FSTRING
get sole--> one by one dir/sub/main/CSTRING >BSTRING
multi string return one by one sub//CSTRING static ASTRING
ect...
ect...

Here is what I have been trying:

sed -i "s|a|ASTRING|g" file.txt

grep [a] file.txt | sed -i "s|a|ASTRING|g"

Repeated for b c f 
Cyrus
  • 84,225
  • 14
  • 89
  • 153
graylagx2
  • 120
  • 1
  • 6
  • That's not a bash question, that's an `sed` question, isn't it? There's a special symbol \b meaning "word boundary" in the regex. – Roland Weber Jun 21 '19 at 20:41
  • Possible duplicate of [sed whole word search and replace](https://stackoverflow.com/questions/1032023/sed-whole-word-search-and-replace) – Roland Weber Jun 21 '19 at 20:41

2 Answers2

2

Use \b in the regular expression to match a word boundary.

sed -i 's/\ba\b/ASTRING/g' file.txt

BTW, you can't use -i if you're piping the input to sed, the filename has to be an argument to sed. If it gets its input from standard input, it doesn't know the filename so it can't update the file in place.

Barmar
  • 741,623
  • 53
  • 500
  • 612
0

nameref variables to the rescue.

a=ASTRING
b=BSTRING
c=CSTRING
f=FSTRING
for v in a b c f
do declare -n R=$v
   sed -Ei "s/\\b$v\\b/$R/g" file.txt
done
Paul Hodges
  • 13,382
  • 1
  • 17
  • 36