You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Bash中echo重定向文件时回车(\r)显示为^M的问题

解决echo命令写入文件时\r显示为^M的问题

问题原因

^M是Unix/Linux系统对Windows回车符(\r)的可视化标记。Unix类系统默认用**换行符(\n)表示换行,而Windows系统采用回车+换行(\r\n)**的组合。你在echo -e命令中手动添加了\r,这些字符被直接写入文件,因此在Unix环境下查看时会被显示为^M。

解决方案

1. 直接移除不必要的\r

如果不需要Windows格式的换行,直接删除命令中的所有\r即可,使用Unix标准的换行方式:

echo -e "<VirtualHost *:80>
                DocumentRoot /var/www/html
                ServerName site
                ServerAlias site
                ErrorLog "/var/log/apache2/html-error.log"
                LogFormat "%t<>%u<>%h<>%O<>%T<>%>s<>%{Referer}i<>%r<>%{User-Agent}i" combined
                CustomLog "/var/log/apache2/html-access.log" combined
                RewriteEngine on
                RewriteCond %{SERVER_NAME} =site
                RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [END,NE,R=permanent]
</VirtualHost>\n" > teste.txt

2. 生成Windows格式的换行(若需要)

如果确实需要生成包含\r\n的Windows格式文件,推荐使用printf代替echo(不同系统的echo对转义字符的支持存在差异,printf行为更一致):

printf "<VirtualHost *:80>\r
                DocumentRoot /var/www/html\r
                ServerName site\r
                ServerAlias site\r
                ErrorLog \"/var/log/apache2/html-error.log\"\r
                LogFormat \"%t<>%u<>%h<>%O<>%T<>%>s<>%{Referer}i<>%r<>%{User-Agent}i\" combined\r
                CustomLog \"/var/log/apache2/html-access.log\" combined\r
                RewriteEngine on\r
                RewriteCond %{SERVER_NAME} =site\r
                RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [END,NE,R=permanent]\r
</VirtualHost>\n" > teste.txt

也可以先生成Unix格式文件,再用unix2dos工具转换:

unix2dos teste.txt

3. 修复已存在的带^M的文件

如果文件已经生成,可通过以下命令移除其中的\r字符:

  • 使用sed:
sed -i 's/\r//g' teste.txt
  • 使用tr:
tr -d '\r' < teste.txt > teste_fixed.txt

内容的提问来源于stack exchange,提问作者Luan De Almeida Pontes

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 11:42:04