chcp 命令更改管道行为

问题描述 投票:0回答:1

有一个脚本

cat.bat
模拟unix
cat
:它从输入流读取然后写入输出流:

@echo off
for /f "tolens=1* delims=:" %%a in ('findstr  /n "^"') do (
  echo(%%b)
)

我可以用两种方式使用它,得到相同的结果:

type textfile | cat.bat
cat.bat < textfile

如果我在 for 循环之前插入行

chcp>nul
,则只有第一种形式(带有
|
)有效。第二个(使用
<
)不输出任何内容。

为什么会这样?以及如何实现行为统一?

batch-file cmd
1个回答
0
投票

这是一种奇怪的行为,我无法解释它,但我可以规避它。

使用

find
代替
findstr
可以解决问题。

@echo off
chcp > NUL

setlocal DisableDelayedExpansion
for /F "delims="  %%a in ('find /n /v ""') do (
    set "line=%%a"
    setlocal EnableDelayedExpansion
    set "line=!line:*]=!"
    echo(!line!
    endlocal
)

我认为根本问题对于 CHCP 来说是特殊的。
它似乎以某些程序无法再从流中读取的方式修改输入流。

测试.bat

@echo off
chcp

echo Read from stdin with findstr
findstr  /n "^"
echo(
echo Read from stdin with find
find /n /v ""


chcp
chcp > CON

测试:

type text.txt | test.bat

活动代码页:850。
使用 findstr 从标准输入读取
1:1号线
2:2号线

使用 find 从 stdin 读取

测试:

test.bat < text.txt

活动代码页:850。
使用 findstr 从标准输入读取

使用 find 从 stdin 读取
[1]1号线
[2]2号线

© www.soinside.com 2019 - 2024. All rights reserved.