【发布时间】:2020-02-14 18:07:35
【问题描述】:
我在以下 C# 字符串中收到一个随机换行符,无法确定输出为何位于两个单独的行上。
我实际上只是尝试以两种不同的方式定义变量。两者产生相同的结果。
string cmdStr = "docker images | grep -E '^prabhasgupte/webmon.*latest' | head -1 | awk '{print $3}'";
Console.Write(cmdStr);
string imageId = commands.Bash(cmdStr);
Console.Write(imageId);
string x = $"docker tag {imageId} scan_target:{imageId}";
Console.Write(x);
这是我收到的输出:
码头工人图片 | grep -E '^prabhasgupte/webmon.*latest' |头-1 | awk '{打印 $3}'
0043699b906f
码头标签 0043699b906f
scan_target:0043699b906f
public static string Bash(this string cmd)
{
var escapedArgs = cmd.Replace("\"", "\\\"");
var process = new Process()
{
StartInfo = new ProcessStartInfo
{
FileName = "/bin/bash",
Arguments = $"-c \"{escapedArgs}\"",
RedirectStandardOutput = true,
UseShellExecute = false,
CreateNoWindow = true,
}
};
process.Start();
string result = process.StandardOutput.ReadToEnd();
process.WaitForExit();
return result;
}
【问题讨论】:
-
您是否为此附加了调试器?两个字符串之一是否可以包含无关的换行符?
-
你可能想仔细看看
Bash()的实现 -
commands.Bash(...)返回的字符串包含换行符。 -
我是not able 在用固定字符串替换
commands.Bash()调用时重现。我想它与该实现有关。查看调试器返回什么 -
string imageId = commands.Bash(cmdStr) + " some test";,试试这个并运行它......它是否将some test分开?或者试试这个Regex.Replace(commands.Bash(cmdStr), @"\t|\n|\r", "");