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

如何在Shell脚本中不使用awk按指定分隔符拆分文件行并格式化输出

需求:不使用awk工具,用Shell脚本拆分并整理input.txt内容

要求按指定规则拆分文件行,将跨多行的标签合并为单行,并拆分连在一起的标签块。

输入文件input.txt内容

<UndefineProperty name="admin.admin.adapters"/>--><!--<AddToProperty 
name="admin.admin.adapters"
value="abc^abc.xz=abc"/>--><Property name="admin.admin.adapters" ride="true"
         targetFile="file/path/file.txt"
         value="abc,xz=abc,xz=com^abc.com.xz=abc,ac=com"/>
<ConfigurationRef xlink:href="file/path/file.xconf"/>
<ConfigurationRef xlink:href="file1.xconf"/>
<ConfigurationRef xlink:href="file2.xconf"/>
<Property name="ac.abc.Password" ride="true"
         targetFile="file/path/abc.properties"
         value="ac.abc.encryptedPassword"/>
<Property name="ac.pqr.Protocol" ride="true"
         targetFile="file/pqr.properties"
         value="https"/>

期望输出格式

<UndefineProperty name="admin.admin.adapters"/>-->
<!--<AddToProperty name="admin.admin.adapters" value="abc^abc.xz=abc"/>-->
<Property name="admin.admin.adapters" ride="true" targetFile="file/path/file.txt" value="abc,xz=abc,xz=com^abc.com.xz=abc,ac=com"/>
<ConfigurationRef xlink:href="file/path/file.xconf"/>
<ConfigurationRef xlink:href="file1.xconf"/>
<ConfigurationRef xlink:href="file2.xconf"/>
<Property name="ac.abc.Password" ride="true" targetFile="file/path/abc.properties" value="ac.abc.encryptedPassword"/>
<Property name="ac.pqr.Protocol" ride="true" targetFile="file/pqr.properties" value="https"/>

已尝试的Shell代码

delimiter="<"
newarray=()

while read -r line ; 
do
  newarray+=( "${line%%"$delimiter"*}" )
  line=${delimiter}${line#*"$delimiter"}
  echo ${line} >> input.txt1
done < input.txt

问题分析

上述代码仅提取了包含<的内容片段,既没有合并跨多行的标签属性,也没有正确拆分连在一起的标签块,无法达到期望效果。

解决方案(纯Shell工具实现,无awk)

以下脚本通过tr和sed组合完成需求:

# 读取文件内容,移除所有换行符,将连续空格替换为单个空格
content=$(tr -d '\n' < input.txt | sed -E 's/[[:space:]]+/ /g')

# 拆分标签块并整理为单行格式
echo "$content" | sed 's/-->/-->\n/g' \
| sed 's/ </\n</g' \
| sed '/^[[:space:]]*$/d'

执行说明

  1. tr -d '\n':移除所有换行符,将整个文件内容合并为单行
  2. sed -E 's/[[:space:]]+/ /g':将连续的空格(包括缩进、换行后的空格)替换为单个空格,规整标签属性格式
  3. sed 's/-->/-->\n/g':在-->后插入换行,拆分第一行中连在一起的标签块
  4. sed 's/ </\n</g':在每个独立标签前插入换行,确保每个标签单独成行
  5. sed '/^[[:space:]]*$/d':移除处理过程中可能产生的空行

若需要将结果保存到文件,可在命令末尾添加> output.txt。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 18:20:40