1

I need to use sed on AIX to find and replace exact match of a string.

as an example we have a like like below

LogicalVolume hdisk1 hdisk10

and I have 2 variables

old_disk=hdisk1
new_disk=hdisk50

Here is the sed command I would like to use

sed "s/"$old_disk"/"$new_disk"/" file1.txt \> file2.txt

The outcome that I get looks like below

LogicalVolume hdisk50 hdisk500

instead of

LogicalVolume hdisk50 hdisk10

Unfortunately < and > do not work on AIX and I don't know how to replace the exact match of variable old_disk. I also tried ' and " around the variable, but it doesn't work neither.

Tobias S.
  • 21,159
  • 4
  • 27
  • 45

2 Answers2

1

Given that perl is available by default on AIX, I'd recommend using it to avoid using disk-related commands with mistaken data!

old_disk=hdisk1
new_disk=hdisk50
export old_disk new_disk
perl -pe 's/\b$ENV{"old_disk"}\b/$ENV{"new_disk"}/g' < file1.txt > file2.txt

This sets the same two variables as your example, then exports them into the environment so that the upcoming perl command can access them. The perl command simply searches and replaces any of the "old_disk" values with "new_disk" values, but restricts the search text by requiring it to have a word boundary on both sides. A word boundary is a change from a word character (alphanumeric and _) to a non-word character (or vice versa).

Jeff Schaller
  • 2,352
  • 5
  • 23
  • 38
0

The sed command is possibly

sed 's/\([[:space:]]\|^\)'"$old_disk"'\([[:space:]]\|$\)/\1'"$new_disk"'\2/' file1.txt > file2.txt

But I don't have an AIX environment to test on.

That looks for old_disk, preceded by whitespace or start of line and followed by whitespace or end of line.

glenn jackman
  • 238,783
  • 38
  • 220
  • 352
  • It's clear why the perl answer is preferable. – glenn jackman Dec 08 '22 at 18:57
  • tested this just now on an AIX box (had a window open from before); it doesn't replace "hdisk1" (the input is unchanged). I'm not savvy enough with sed to say why it failed :/ – Jeff Schaller Dec 08 '22 at 19:04
  • looks like if I replace the whole `[[:space:]]|^` with just a plain old space, it works ... looking more like the alternation maybe – Jeff Schaller Dec 08 '22 at 19:06
  • The line is prefixed with "`LogicalVolume`" so the `^` won't be effective here. I still can't get the `([[:space:]]\|$` alternation to work. I think you'd have to hack around it with two expressions (one for mid-line matches and one for EOL matches) – Jeff Schaller Dec 08 '22 at 19:17
  • different seds may or may not need the escape before the pipe and/or parentheses – glenn jackman Dec 08 '22 at 22:11