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

如何在Bash中拼接字符串与文件并保留字面量\newpage

问题描述

我是Bash新手,正尝试将多个Markdown文件合并为一个。当前合并文件时可保留\newpage行,但通过echo调用字符串添加组标题时,无法保留字面量\newpage。希望不通过单独创建存储组名加\newpage的文件来实现需求。

现有可正常保留\newpage的合并代码:

dir_in="/path/do/input_directory/"
dir_out="/path/do/output_directory/"
file="group_1"
for f in ${dir_in}${file}/*.md; do cat $f >> ${dir_out}${file}.md; echo >> ${dir_out}${file}.md; done

曾尝试的代码(无法保留\newpage):

title="#Title of group 1 \newpage"
content=$(cat "${dir_out}${file}.md")
result=$(echo "${title}\n\n${content}")
echo "$result" > ${dir_out}${file}.md

问题出在echo会自动解析转义字符,导致\newpage被拆分成换行和“ewpage”。

期望输出示例:

# Title of group 1

\newpage

## Item 1 of group 1

Text to item 1 of group 1.

\newpage
...
解决方案

方法1:用printf替代echo,先写标题再合并文件

printf不会自动解析转义字符(除非指定%b格式符),可以精准控制输出内容。直接先把标题写入输出文件,再合并所有Markdown文件:

dir_in="/path/do/input_directory/"
dir_out="/path/do/output_directory/"
file="group_1"
# 标题里用\\newpage表示字面量\newpage,\n用于换行
title="# Title of group 1\n\n\\newpage\n\n"

# 先写入标题到输出文件(覆盖原有内容)
printf "%b" "$title" > "${dir_out}${file}.md"

# 遍历合并所有md文件
for f in "${dir_in}${file}"/*.md; do
    cat "$f" >> "${dir_out}${file}.md"
    echo >> "${dir_out}${file}.md"  # 添加空行分隔不同文件
done

方法2:用Here-doc插入标题到已合并文件前

如果已经完成文件合并,想要在开头插入标题,用Here-doc可以原样输出所有内容,不会解析转义字符:

dir_in="/path/do/input_directory/"
dir_out="/path/do/output_directory/"
file="group_1"

# 先把所有文件合并到临时文件
tmp_file="${dir_out}tmp_${file}.md"
for f in "${dir_in}${file}"/*.md; do
    cat "$f" >> "$tmp_file"
    echo >> "$tmp_file"
done

# 用Here-doc将标题和临时文件内容合并到最终文件
cat > "${dir_out}${file}.md" <<EOF
# Title of group 1

\newpage

$(cat "$tmp_file")
EOF

# 清理临时文件
rm "$tmp_file"

方法3:修复原有代码的变量定义和输出方式

如果想保留原有代码的逻辑,只需修改变量定义和输出命令:

dir_in="/path/do/input_directory/"
dir_out="/path/do/output_directory/"
file="group_1"

# 先执行原合并逻辑
for f in "${dir_in}${file}"/*.md; do cat "$f" >> "${dir_out}${file}.md"; echo >> "${dir_out}${file}.md"; done

# 方法A:用单引号定义变量,避免转义
title='# Title of group 1 \newpage'
content=$(cat "${dir_out}${file}.md")
# 用printf输出换行和内容
printf "%s\n\n%s" "$title" "$content" > "${dir_out}${file}.md"

# 或者方法B:双引号里转义反斜杠
# title="# Title of group 1 \\newpage"
# content=$(cat "${dir_out}${file}.md")
# printf "%s\n\n%s" "$title" "$content" > "${dir_out}${file}.md"

内容的提问来源于stack exchange,提问作者ThinkRat

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 05:16:18