我知道color bf命令设置了整个命令行窗口的颜色,但我想打印不同颜色的单行。
当前回答
这是一个自编译的bat/.net混合物(应该保存为。bat),可以在任何安装了。net框架的系统上使用(即使是最古老的XP/2003安装,也很少看到没有。net框架的windows)。它使用jscript.net编译器创建一个exe,能够打印字符串与不同的背景/前景色仅为当前行。
@if (@X)==(@Y) @end /* JScript comment
@echo off
setlocal
for /f "tokens=* delims=" %%v in ('dir /b /s /a:-d /o:-n "%SystemRoot%\Microsoft.NET\Framework\*jsc.exe"') do (
set "jsc=%%v"
)
if not exist "%~n0.exe" (
"%jsc%" /nologo /out:"%~n0.exe" "%~dpsfnx0"
)
%~n0.exe %*
endlocal & exit /b %errorlevel%
*/
import System;
var arguments:String[] = Environment.GetCommandLineArgs();
var newLine = false;
var output = "";
var foregroundColor = Console.ForegroundColor;
var backgroundColor = Console.BackgroundColor;
var evaluate = false;
var currentBackground=Console.BackgroundColor;
var currentForeground=Console.ForegroundColor;
//http://stackoverflow.com/a/24294348/388389
var jsEscapes = {
'n': '\n',
'r': '\r',
't': '\t',
'f': '\f',
'v': '\v',
'b': '\b'
};
function decodeJsEscape(_, hex0, hex1, octal, other) {
var hex = hex0 || hex1;
if (hex) { return String.fromCharCode(parseInt(hex, 16)); }
if (octal) { return String.fromCharCode(parseInt(octal, 8)); }
return jsEscapes[other] || other;
}
function decodeJsString(s) {
return s.replace(
// Matches an escape sequence with UTF-16 in group 1, single byte hex in group 2,
// octal in group 3, and arbitrary other single-character escapes in group 4.
/\\(?:u([0-9A-Fa-f]{4})|x([0-9A-Fa-f]{2})|([0-3][0-7]{0,2}|[4-7][0-7]?)|(.))/g,
decodeJsEscape);
}
function printHelp( ) {
print( arguments[0] + " -s string [-f foreground] [-b background] [-n] [-e]" );
print( " " );
print( " string String to be printed" );
print( " foreground Foreground color - a " );
print( " number between 0 and 15." );
print( " background Background color - a " );
print( " number between 0 and 15." );
print( " -n Indicates if a new line should" );
print( " be written at the end of the ");
print( " string(by default - no)." );
print( " -e Evaluates special character " );
print( " sequences like \\n\\b\\r and etc ");
print( "" );
print( "Colors :" );
for ( var c = 0 ; c < 16 ; c++ ) {
Console.BackgroundColor = c;
Console.Write( " " );
Console.BackgroundColor=currentBackground;
Console.Write( "-"+c );
Console.WriteLine( "" );
}
Console.BackgroundColor=currentBackground;
}
function errorChecker( e:Error ) {
if ( e.message == "Input string was not in a correct format." ) {
print( "the color parameters should be numbers between 0 and 15" );
Environment.Exit( 1 );
} else if (e.message == "Index was outside the bounds of the array.") {
print( "invalid arguments" );
Environment.Exit( 2 );
} else {
print ( "Error Message: " + e.message );
print ( "Error Code: " + ( e.number & 0xFFFF ) );
print ( "Error Name: " + e.name );
Environment.Exit( 666 );
}
}
function numberChecker( i:Int32 ){
if( i > 15 || i < 0 ) {
print("the color parameters should be numbers between 0 and 15");
Environment.Exit(1);
}
}
if ( arguments.length == 1 || arguments[1].toLowerCase() == "-help" || arguments[1].toLowerCase() == "-help" ) {
printHelp();
Environment.Exit(0);
}
for (var arg = 1; arg <= arguments.length-1; arg++ ) {
if ( arguments[arg].toLowerCase() == "-n" ) {
newLine=true;
}
if ( arguments[arg].toLowerCase() == "-e" ) {
evaluate=true;
}
if ( arguments[arg].toLowerCase() == "-s" ) {
output=arguments[arg+1];
}
if ( arguments[arg].toLowerCase() == "-b" ) {
try {
backgroundColor=Int32.Parse( arguments[arg+1] );
} catch(e) {
errorChecker(e);
}
}
if ( arguments[arg].toLowerCase() == "-f" ) {
try {
foregroundColor=Int32.Parse(arguments[arg+1]);
} catch(e) {
errorChecker(e);
}
}
}
Console.BackgroundColor = backgroundColor ;
Console.ForegroundColor = foregroundColor ;
if ( evaluate ) {
output=decodeJsString(output);
}
if ( newLine ) {
Console.WriteLine(output);
} else {
Console.Write(output);
}
Console.BackgroundColor = currentBackground;
Console.ForegroundColor = currentForeground;
下面是帮助信息:
例子:
Coloroutput.bat -s "aa\nbb\n\u0025cc" -b 10 -f 3 -n -e
您还可以在这里找到这个脚本。
你也可以检查卡洛斯的颜色功能-> http://www.dostips.com/forum/viewtopic.php?f=3&t=4453
其他回答
我刚从Win 7 Home转换到Win 10 Pro,想要替换我从其他批次调用的批量,以颜色回显信息。回顾上面讨论的内容,我使用以下内容,这将直接取代我的前一批。注意在消息中添加“~”,可以使用带有空格的消息。我不用记住代码,而是用字母来代表我需要的颜色。
如果%2包含空格,则需要“…” 黑色底色:R=红色G=绿色Y=黄色W=白色
ECHO OFF
IF "%1"=="R" ECHO ^[91m%~2[0m
IF "%1"=="G" ECHO ^[92m%~2[0m
IF "%1"=="Y" ECHO ^[93m%~2[0m
IF "%1"=="W" ECHO ^[97m%~2[0m
最简单的方法是像这样对powershell进行系统调用:
s=os.system('powershell Write-Host "I am so bored with this. Work already" -ForegroundColor Blue')
否则:
←[94mPff
下面的代码由两部分组成。如果方便的话,在这个。cmd文件中还有一个。txt格式的文件,在“double”行(====)下面。
::adonios77
::This is a .cmd file
@ECHO OFF
TITLE Colored Command Prompt echoes HELP
mode con: cols=55 lines=47
CLS
COLOR 0f
echo [93m
ECHO This is just help, as optical example,
ECHO when make or modify colorful command prompt echoes.
ECHO.
ECHO More info in Source:
ECHO [4m[94mhttps://stackoverflow.com/questions/2048509/how-to-echo-with-different-colors-in-the-windows-command-line[0m
ECHO.
ECHO [0mESC[0m "Text" Default colours Text[0m
ECHO [7mESC[7m "Text" Inversed Back-Fore colors[0m
ECHO [101mESC[101m "Text" in Red Background[0m
ECHO [91mESC[91m "Text" in Red Foreground)[0m
echo.
echo To make an ESC special character, (ASCII Escape code)
echo open or edit a .txt or .bat or .cmd file,
echo (hold)L-Alt and (type)027 in NumPad)
echo Or, in Command Prompt, (can't copy/paste special char.)
echo just press Ctrl+[
echo (it should look like: "echo ^[[33m'Text'^[[0m")
echo.
echo STYLES
echo [0mESC[0m Reset[0m
echo [1mESC[1m Bold [90m*This is not work for me[0m
echo [4mESC[4m Underline[0m
echo [7mESC[7m[0m Inverse
echo.
echo COLORS# Foreground-Background (color /? HEX) && echo.
echo [90mDark[0m / [100mLight[0m
echo Fore-Back / Fore-Back
echo Black * [100m[30m30[0m-[4m[40m40 [0m (0) / (8) [90m90[0m-[100m100 [0m
echo Red [31m31[0m-[41m41 [0m (4) / (C) [91m91[0m-[101m101 [0m
echo Green [32m32[0m-[42m42 [0m (2) / (A) [92m92[0m-[102m102 [0m
echo Yellow [33m33[0m-[90m[43m43 [0m (6) / (E) [93m93[0m-[90m[103m103 [0m
echo Blue [34m34[0m-[44m44 [0m (1) / (9) [94m94[0m-[104m104 [0m
echo Magenta [35m35[0m-[45m45 [0m (5) / (D) [95m95[0m-[105m105 [0m
echo Cyan [36m36[0m-[46m46 [0m (3) / (B) [96m96[0m-[106m106 [0m
echo White * [37m37[0m-[47m47 [0m (7) / (F) [97m97[0m-[7;97m107 [0m
echo.
echo Note: use ESC[0m at the end of (every) line.
echo.
echo COMBINATIONS
echo [7;91mESC[7;91m inverse red foreground color ESC[0m[0m
echo.
ECHO. && PAUSE
exit
============================================================
:: This is a .txt file.
This is just help, as optical example,
when make or modify colorful command prompt echoes.
More info in Source:
https://stackoverflow.com/questions/2048509/how-to-echo-with-different-colors-in-the-windows-command-line
To make an ESC special character, (),
open or edit a .txt or .bat or .cmd file,
(hold)L-Alt and (type)027 in NumPad)
STYLES
[0m Reset
[1m Bold
[4m Underline
[7m Inverse
COLORS# (Foreground-Background)
Dark / Light
Fore-Back / Fore-Back
Black 30-40 (0) / (8) 90-100
Red 31-41 (4) / (C) 91-101
Green 32-42 (2) / (A) 92-102
Yellow 33-43 (6) / (E) 93-103
Blue 34-44 (1) / (9) 94-104
Magenta 35-45 (5) / (D) 95-105
Cyan 36-46 (3) / (B) 96-106
White 37-47 (7) / (F) 97-107
COMBINATIONS
ESC[7;31m inverse red foreground color 0m
Note: use ESC[0m at the end of (every) line.
examples:
@ECHO OFF
ECHO Default Text
ECHO [7m"Text" Inversed Back-Fore colors (7m)[0m
ECHO [101m"Text" in Red Background (101m)[0m
ECHO [91m"Text" in Red Foreground (91m)[0m
============================================================
另外,我发现用这种方式可以改变命令提示符的样子,暂时的或永久的。 下面的TEXT代码是一个例子:
This is a .txt file. Antony's examples: prompt $Q$Q$Q$Q$Q$Q$Q$Q$Q$Q$Q$Q$Q$Q$Q$Q$Q$Q$Q$Q$S $T$_ $P\$_$G gives something like that: ==================== 19:53:02,73 C:\Windows\system32\ > For All Users & Permanent: (if there is space between characters, must double quoted [""]) SETX PROMPT /M $Q$Q$Q$Q$Q$Q$Q$Q$Q$Q$Q$Q$Q$Q$Q$Q$Q$Q$Q$Q$S$S$T$_$_$S$P\$_$G$S gives something like that: ==================== 9:01:23,17 C:\Windows\system32\ > NOTE: Variables created or modified by SETX will be available at the next logon session.
现在让我们给上面的例子配上颜色。结果如上图所示。
彩色提示示例:
仅适用于当前用户:
prompt $E[91m$E[40m$Q$Q$Q$Q$Q$Q$Q$Q$Q$Q$Q$Q$Q$Q$Q$Q$Q$Q$Q$Q$S $T$E[93m$_ $P\$_$G$E[0m
or
对于所有用户和永久用户:
SETX PROMPT /M $E[91m$E[40m$Q$Q$Q$Q$Q$Q$Q$Q$Q$Q$Q$Q$Q$Q$Q$Q$Q$Q$Q$Q$S$S$T$E[93m$_$_$S$P\$_$G$S$E[0m
你可以用cecho..你也可以用它来嵌入到你的脚本中,这样你就不必随身携带。com或。exe文件了
http://www.codeproject.com/Articles/17033/Add-Colors-to-Batch-Files
为非windows 10用户提供了一个不需要调用标签的选项,避免了这样做带来的延迟。
下面是findstr colorprint例程的宏版本
usage -其中BF被替换为背景/前景色的十六进制数字值: %Col%{BF}{"要打印的字符串"}
@Echo off & CD "%TEMP%"
For /F "tokens=1,2 delims=#" %%a in ('"prompt #$H#$E# & echo on & for %%b in (1) do rem"') do (set "DEL=%%a")
Set "Col=For %%l in (1 2)Do if %%l==2 (Set "_Str="&(For /F "tokens=1,2 Delims={}" %%G in ("!oline!")Do Set "C_Out=%%G" & Set "_Str=%%~H")&(For %%s in (!_Str!)Do Set ".Str=%%s")&( <nul set /p ".=%DEL%" > "!_Str!" )&( findstr /v /a:!C_Out! /R "^$" "!_Str!" nul )&( del " !_Str!" > nul 2>&1 ))Else Set Oline="
Setlocal EnableDelayedExpansion
rem /* concatenation of multiple macro expansions requires the macro to be expanded within it's own code block. */
(%Col%{02}{"green on black,"}) & (%Col%{10}{black on blue})
Echo/& (%Col%{04}{red on black}) & (%Col%{34}{" red on blue"})
Goto :Eof
一个更健壮的宏版本,充满了错误处理。
@Echo off & PUSHD "%TEMP%"
rem /* Macro Definitions */
(Set \n=^^^
%= macro newline Do not modify =%
)
(Set LF=^
%= linefeed. Do not modify =%)
If "!![" == "[" (
Echo/%%COL%% macro must be defined prior to delayed expansion being enabled
Goto :end
)
For /F "tokens=1,2 delims=#" %%a in ('"prompt #$H#$E# & echo on & for %%b in (1) do rem"') do (set "DEL=%%a")
rem /* %hCol% - Alternate color macro; escaped for use in COL macro. No error checking. Usage: (%hCol:?=HEXVALUE%Output String) */
Set "hCol=For %%o in (1 2)Do if %%o==2 (^<nul set /p ".=%DEL%" ^> "!os!" ^& findstr /v /a:? /R "^$" "!os!" nul ^& del "!os!" ^> nul 2^>^&1 )Else Set os="
rem /* %TB% - used with substitution within COL macro to format help output; not fit for general use, */
Set "TB=^&^< nul Set /P "=.%DEL%!TAB!"^&"
rem /* %COL% - main color output macro. Usage: (%COL%{[a-f0-9][a-f0-9]}{String to Print}) */
Set COL=Set "_v=1"^&Set "Oline="^& For %%l in (1 2)Do if %%l==2 (%\n%
If not "!Oline!" == "" (%\n%
Set "_Str="%\n%
For /F "tokens=1,2 Delims={}" %%G in ("!oline!")Do (%\n%
Set "Hex=%%G"%\n%
Set "_Str=%%~H"%\n%
)%\n%
Echo/!Hex!^|findstr /RX "[0-9a-fA-F][0-9a-fA-F]" ^> nul ^|^| (Echo/^&(%hCol:?=04%Invalid - )%TB%(%hCol:?=06%Bad Hex value.)%TB%(%hCol:?=01%%%COL%%{!Hex!}{!_Str!})%TB:TAB=LF%(%hCol:?=02%!Usage!)^&Set "_Str="^&Set "_v=0")%\n%
If not "!_Str!" == "" (%\n%
^<nul set /p ".=%DEL%" ^> "!_Str!"%\n%
findstr /v /a:!Hex! /R "^$" "!_Str!" nul %\n%
del "!_Str!" ^> nul 2^>^&1%\n%
)Else If not !_v! EQU 0 (%\n%
Echo/^&(%hCol:?=04%Invalid -)%TB%(%hCol:?=06%Arg 2 absent.)%TB%(%hCol:?=01%%%COL%%!Oline!)%TB:TAB=LF%(%hCol:?=04%Input is required for output string.)%TB:TAB=LF%(%hCol:?=02%!Usage!)%\n%
)%\n%
)Else (Echo/^&(%hCol:?=04%Invalid -)%TB%(%hCol:?=06%No Args)%TB:TAB=!TAB!!TAB!%(%hCol:?=01%%%COL%%!Oline!)%TB:TAB=LF%(%hCol:?=02%!Usage!))%\n%
)Else Set Oline=
Set "usage=%%COL%%{[a-f0-9][a-f0-9]}{String to Print}"
For /F eol^=^%LF%%LF%^ delims^= %%A in ('forfiles /p "%~dp0." /m "%~nx0" /c "cmd /c echo(0x09"') do Set "TAB=%%A"
rem /* removes escaping from macros to enable use outside of COL macro */
Set "hCol=%hCol:^=%"
Set "TB=%TB:^=%"
Setlocal EnableDelayedExpansion
rem /* usage examples */
(%COL%{02}{"green on black,"}) & (%COL%{10}{"black on blue"})
Echo/
(%COL%{04}{"red on black"}) & (%COL%{34}{" red on blue"})&(%COL%{40}{"black on red"})
Echo/& %COL%{03}{Demonstration of error handling-}
rem /* error handling */
Echo/%TB:TAB=!LF! % %hCol:?=20%Example 1 - No args
%COL%
Echo/%TB:TAB=!LF! % %hCol:?=20%Example 2 - Missing 2nd Arg
%COL%{ff}
Echo/%TB:TAB=!LF! % %hCol:?=20%Example 3 - Invalid hex value for 1st Arg
%COL%{HF}{string}
Echo/%TB:TAB=!LF! % %hCol:?=0d%Done
:end
POPD
Goto :Eof
推荐文章
- Android-Facebook应用程序的键散列
- 如何在PowerShell中输出一些东西
- 从matplotlib中的颜色映射中获取单个颜色
- 更改UITextField和UITextView光标/插入符颜色
- 如何在命令提示符中使用空格?
- 在Python中如何在Linux和Windows中使用“/”(目录分隔符)?
- 命令行从操作系统级配置中删除环境变量
- 在特定的文件夹中打开Cygwin
- 命令行svn for Windows?
- Gulp命令未找到-安装Gulp后错误
- 如何找到并运行keytool
- 我的Windows应用程序的图标应该包括哪些大小?
- 如何使用xargs复制名称中有空格和引号的文件?
- 在Windows上设置Python simpleHTTPserver
- 如何从批处理文件运行PowerShell脚本