帮助更换SED

帮助更换SED

我想替换 C:\Documents and Settings\sjohnson4\AppData\Local\Microsoft\Teams\current\Squirrel.exeC:\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\\/'

结果是

C:\Documents and Settings\USERNAME\sjohnson4\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\\/'

回报

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

有任何想法吗?

答案1

如果我明白你的要求,这应该对你有用,如果将“sjohnson4”替换为用户名。

sed 's/sjohnson4/USERNAME/'

这将搜索并替换 sjohnson4 如果这不是您需要的,请告诉我。

杰森·C.

答案2

使用反斜杠 ( \) 作为字段分隔符,以下代码将无条件地awk将第三个字段替换为字符串USERNAME

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

测试:

$ 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

与上面类似的方法使用sed

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

[^\]*\\这会将(任意数量的非反斜杠,后跟反斜杠)的第三个匹配项替换为字符串USERNAME\

测试:

$ 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

答案3

如果你想匹配其中的任何“用户名”

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

例子:

$ 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

答案4

只需进行最少的更改即可更正您的脚本:

$ 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

相关内容