在字符串中特定数量的字符后添加换行符

Adding a new-line after a specific number of characters in a string

我找到了这个帖子:

How to insert a new line character after a fixed number of characters in a file

但不幸的是那里的答案对我没有帮助。

我有一个巨大的字符串 $temp,我想在特定数量的字符(例如 20 个)之后将其截断,以便与上面的行匹配。在该字符数之后应添加一个 \n,最后应将格式化的字符串插入到变量中。如果字符串的长度<数字,则不应切割。

现在我坚持

sed -e "s/.\{20\}/&\n/g" <<< $temp

但它不起作用。不是添加 \n,而是添加空格。

最简单的方法可能是使用 fold 实用程序,如您引用的线程中所建议的那样。例如:

printf "%s\n" "$temp" | fold -cw 20

当你说:

to match it with the line above

...也许尝试使用 uniq 程序来清除(或计数)重复项会有所帮助:

printf "%s\n" "$temp" | fold -cw 20 | uniq

当然,如果你想在一个新变量中输出,将它包装在 $() 中,如下所示:

new="$(printf "%s\n" "$temp" | fold -cw 20 | uniq)"
NewTemp="$( printf "%s" "${temp}" | sed -e 's/.\{20\}/&\
/g' )"
  • 你的 sed 很好,但如果应用程序没有特别考虑到这一点(比如 GNU sed 的选项 -i),那么当源和目标相同时它总是有点棘手。
  • 尽可能使用单引号(不需要替换)
  • 我更喜欢使用真正的新行(当不在线时)而不是 \n 以在每个 sed 版本上使用(posix 不允许在替换模式中使用 \n
  • 只需确定 temp 变量中现有新行的含义
    • sed 默认每行工作一行(所以每行一行一行)
    • 如果使用多行(选项或加载缓冲区),换行也是一个字符 .