Home > Software design >  AIX sed - find exact match and replace
AIX sed - find exact match and replace

Time:12-09

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.

CodePudding user response:

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).

CodePudding user response:

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.

  • Related