我有一个包含如下内容的文件:
<key>CFBundleName</key>
<string>${PRODUCT_NAME}</string>
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleShortVersionString</key>
<string>8.10</string>
<key>CFBundleURLTypes</key>
要使用 CFBundleShortVersionString 提取该行,我可以使用:
(for /f "delims=," %a in ('type "Info.pList" ^|findstr "CFBundleShortVersionString"') do @echo %a) > "CFBundleShortVersionString.txt"
提供输出
<key>CFBundleShortVersionString</key>
但是我该如何提取下面的行呢?即
<string>8.10</string>
我在 Windows 10 中使用命令提示符。
谢谢, 克里斯.
您可以首先确定包含搜索字符串的行号,然后读取文件并跳过该行数,如以下批处理文件所示:
@echo off
setlocal EnableExtensions DisableDelayedExpansion
rem // Initialise variables:
set "LineNumber=" & set "LineString="
rem // Let `findstr` precede the matching line(s) with line number plus a colon:
for /F "delims=:" %%L in ('findstr /N "CFBundleShortVersionString" "Info.pList"') do (
rem // Fetch the line number (remove `if defined LineNumber` if you want the last match):
if not defined LineNumber set /A "LineNumber=%%L"
)
rem // Check whether the search string has been found:
if defined LineNumber (
rem // Read the file but skip lines up to the one containing the search string:
for /F "usebackq skip=%LineNumber% delims=" %%S in ("Info.pList") do (
rem // This captures the next (non-empty) line following the one containing the search string:
if not defined LineString set "LineString=%%S"
)
)
rem // Return result:
echo This is the extracted line: "%LineString%"
endlocal
exit /B
如果您只需要这两行,那么我们就使用这个技巧
您可以将其粘贴到 CLI 中:
SET "_Found="
@for /f "delims=," %a in ('
Type "Info.pList"
') do @(
IF NOT DEFINED _Found (
ECHO=%a|find "CFBundleShortVersionString" && (
SET "_Found=1"
)
) ELSE (
ECHO=%a
SET "_Found="
)
)>> "CFBundleShortVersionString.txt"
这将输出每场比赛以及每场比赛后的第一行
这是使用正则表达式获取下一行的一种方法。 Select-String 不是 sed 或 awk,但它可以做一些事情。
FOR /F "delims=" %%A IN ('powershell -NoLogo -NoProfile -Command ^
"(Get-Content -Path C:\src\t\Get-NextLine.txt -Raw |" ^
"Select-String -Pattern 'CFBundleShortVersionString.*\n(.*)\n').Matches.Groups[1].Value"') DO (
SET "NEXT_LINE=%%~A"
)
ECHO NEXT_LINE is "%NEXT_LINE%"
如果目标是从线上获得
8.10
,那么在 -Pattern 上多做一点工作就可以做到这一点。
注意:如果使用
ECHO %NEXT_LINE%
,则将解释重定向字符 <>
。这就是为什么最后一个输出行使用引号字符。