首页 > 解决方案 > 如何在 Linux 中使用 sed 将文本文件拆分为 10+ 个字符的块而不分割单词?

问题描述

我想提出一个 sed 命令,其中每 10 个字符将查找最近的空格并将其替换为“|”

我试过sed -E -e 's/ /|/\( *?[0-9a-zA-Z]*\)\{10,\}' new.file了,但它显示错误。

示例输入:

Hello there! How are you? I am trying to figure this out.

预期输出:

Hello there!|How are you?|I am trying|to figure this|out.

标签: linuxunixsed

解决方案


这适用于给定的样本:

$ sed -E 's/(.{10}[^ ]*) /\1|/g' ip.txt
Hello there!|How are you?|I am trying|to figure this|out.
  • (.{10}[^ ]*)这匹配 10 个字符,后跟任何非空格字符
  • 然后匹配一个空格
  • \1|放回捕获的部分和一个|角色

推荐阅读