-1

I want to replace C:\Documents and Settings\sjohnson4\AppData\Local\Microsoft\Teams\current\Squirrel.exe with C:\Documents and Settings\USERNAME\AppData\Local\Microsoft\Teams\current\Squirrel.exe.

echo "C:\Documents and Settings\sjohnson4\AppData\Local\Microsoft\Teams\current\Squirrel.exe" | \
    sed  -e 's/\\Documents and Settings\\*\\/\\Documents and Settings\\USERNAME\\/'

results in

C:\Documents and Settings\USERNAME\sjohnson4\AppData\Local\Microsoft\Teams\current\Squirrel.exe

while

echo "C:\Documents and Settings\sjohnson4\AppData\Local\Microsoft\Teams\current\Squirrel.exe" | \
    sed  -e 's/\\Documents and Settings\\.*\\/\\Documents and Settings\\USERNAME\\/'

returns

C:\Documents and Settings\USERNAME\Squirrel.exe

Any ideas?

4 Answers 4

3

If I understand what your asking this should work for you if will replace "sjohnson4" with USERNAME.

sed 's/sjohnson4/USERNAME/'

This will search for and replace sjohnson4 if this isn't what you need let me know.

Jason C.

1

Using backslash (\) as a field separator, the following would use awk to replace the 3rd field with the string USERNAME unconditionally:

awk -F '\' 'BEGIN { OFS = FS } { $3 = "USERNAME"; print }'

Testing:

$ printf '%s\n' 'C:\Documents and Settings\sjohnson4\AppData\Local\Microsoft\Teams\current\Squirrel.exe' | awk -F '\' 'BEGIN { OFS = FS } { $3 = "USERNAME"; print }'
C:\Documents and Settings\USERNAME\AppData\Local\Microsoft\Teams\current\Squirrel.exe

A similar approach as the above using sed:

sed 's/[^\]*\\/USERNAME\\/3'

This replaces the 3rd match of [^\]*\\ (any number of non-backslashes, followed by a backslash) with the string USERNAME\.

Testing:

$ printf '%s\n' 'C:\Documents and Settings\sjohnson4\AppData\Local\Microsoft\Teams\current\Squirrel.exe' | sed 's/[^\]*\\/USERNAME\\/3'
C:\Documents and Settings\USERNAME\AppData\Local\Microsoft\Teams\current\Squirrel.exe
0

If you want to match any "username" in there

sed -E "s,(^.+and Settings\\\)[A-Za-z0-9]+(\\\AppData.+$),\1USERNAME\2,"

Example:

$ echo "C:\Documents and Settings\ThisIsAnotherUsername15\AppData\Local\Microsoft\Teams\current\Squirrel.exe" | sed -E "s,(^.+and Settings\\\)[A-Za-z0-9]+(\\\AppData.+$),\1USERNAME\2," 
C:\Documents and Settings\USERNAME\AppData\Local\Microsoft\Teams\current\Squirrel.exe
0

To just correct your script with minimal changes:

$ echo 'C:\Documents and Settings\sjohnson4\AppData\Local\Microsoft\Teams\current\Squirrel.exe' |
    sed 's/\(\\Documents and Settings\\\)[^\\]*/\1USERNAME/'
C:\Documents and Settings\USERNAME\AppData\Local\Microsoft\Teams\current\Squirrel.exe

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .