每次打开 Windows 终端时,我都会运行一个名为的文件doskeys.cmd
来设置命令别名等。
应该composer.json
存在,我想从中提取 PHP 版本,以便我可以动态设置我的终端以使用该版本的 PHP。
例子composer.json
:
{
"license": "MIT",
"require": {
"php": "^8.4",
"mekras/php-speller": "^2.3.0"
},
"scripts": {
"post-root-package-install": "@php -r \"file_exists('.env') || copy('.env.example', '.env');\""
},
"config": {
"platform": {
"php": "8.4.4"
}
}
}
从这个文件中提取8.4
(第 4 行)。
这是我目前拥有的代码:
if exist composer.json (
for /f "tokens=1,2 delims=: " %%a in (composer.json) do (
echo %%a|findstr /b """php"": """^">nul
if '%errorlevel%' EQU '0' set php=%%b
)
)
if exist composer.json echo %path%|findstr /b "C:\PHP">nul || set path=C:\PHP\php-%php%;%PATH%
然而,它存在两个问题。
findstr
不会忽略不包含的行"php": "^
(这对于我需要提取的行来说是唯一的),所以我的代码只有"php": "^8.4",
在最后一行才有效。- 我只能提取
"^8.4",
(而不是8.4
)