BDubs
BDubs

Reputation: 73

Replace character in substring after character using SED or AWK

I have a dynamic string and need to replace a character within the string but only in the last portion of the string.

Example String:

Microsoft|Application-Local|Installed on system|win:application-local

I need to replace the "-" in the string with a ":" but only in the last portion of the string.

Desired String:

Microsoft|Application-Local|Installed on system|win:application:local

The data in the string changes with the exception of the "win:". Would it be possible to say starting at "win:" look to the end of the string replace any "-" with ":"

I am having a hard time getting my logic straight.

Upvotes: 0

Views: 355

Answers (3)

Ed Morton
Ed Morton

Reputation: 203169

$ awk 'BEGIN{FS=OFS="|"} {sub(/-/,":",$NF)} 1' file
Microsoft|Application-Local|Installed on system|win:application:local

Some (maybe all, idk - test them) of the other solutions posted so far would work for the 1 sample input line you provided but fail given different input such as input that doesn't have a - in that final field or input that doesn't have some specific strings like win in the final field or does have it in an earlier field, etc. so you might want to come up with some more comprehensive input/output covering all of your use cases to test against.

Upvotes: 1

x1n13y84issmd42
x1n13y84issmd42

Reputation: 970

If using sed or awk is not mandatory then shell parameter expansion to the rescue:

STR="Microsoft|Application-Local|Installed on system|win:application-local"
echo ${STR%-*}:${STR##*-}

In the snippet above

${STR%-*} means "STR without the shortest match of the -* regexp from the tail"

and ${STR##*-} means "STR without the longest of the *- regexp from the head"

Upvotes: 1

dawg
dawg

Reputation: 103714

Given:

$ s='Microsoft|Application-Local|Installed on system|win:application-local'

With sed:

$ echo "$s" | sed -e 's/\(win:[^-]*\)-\([^-]*$\)/\1:\2/'
Microsoft|Application-Local|Installed on system|win:application:local

Or Perl:

$ echo "$s" | perl -lpe 's/(win:[^-]*)-([^-]*)$/\1:\2/'
Microsoft|Application-Local|Installed on system|win:application:local

If the win:... part is always the last, you don't need the second capturing group.

Upvotes: 2

Related Questions