首页 > 解决方案 > 用 \n+numbers+\n 替换所有数字

问题描述

我想用换行符+数字+换行符替换字符串中的所有数字。

更改字符串

1xxx2yyy3zzz

进入

  1
  xxx
  2
  yyy
  3
  zzz

他们俩都不能出招。

echo "1xxx2yyy3zzz"  |tr  '0-9'  '\n0-9\n'
echo "1xxx2yyy3zzz"  |tr  '[0-9]'  '\n[0-9]\n'
echo "1xxx2yyy3zzz"  |tr  [:digit:]    \n[:digit:]\n

标签: bashawksedtr

解决方案


考虑到您的 Input_file 与显示的示例相同,那么以下内容可能会对您有所帮助。

sed -E 's/[a-zA-Z]+/\n&\n/g;s/\n$//' Input_file

说明:现在也为上述代码添加说明。它仅用于解释目的。

sed -E '       ##Starting sed here and -E option is for extended regex enabling it.
s              ##s is for substitution.
/[a-zA-Z]+/    ##look for regex all small of capital letter alphabets and substitute them with following regex.
\n&\n/         ##Substitute above match with a NEW line matched value and a NEW line here.
g;             ##g means perform this action to all matched patterns on current line.
s/             ##Starting a new substitution here.
\n$            ##Substituting NEW LINE which is coming in last of the line with following.
//             ##Substituting above with NULL.
' Input_file   ##Mentioning Input_file name here.

推荐阅读