【问题标题】:replace all numbers with \n+numbers+\n用 \n+numbers+\n 替换所有数字
【发布时间】:2019-01-05 22:20:35
【问题描述】:

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

更改字符串

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

【问题讨论】:

  • tr 不做正则表达式,试试sed
  • 定义数字。 +3.14159e-22 是数字吗?如果你只想要整数(或者甚至只想要 positive 整数),你应该说清楚。

标签: bash awk sed tr


【解决方案1】:

使用python3。

>>> import re
>>> string="1xxx2yyy3zzz"
>>> print(re.sub('(\d+)',r'\n\1\n',string))

1
xxx
2
yyy
3
zzz
>>> print(re.sub('(\d+)',r'\n\1\n',string).strip())
1
xxx
2
yyy
3
zzz

【讨论】:

    【解决方案2】:

    这可能对你有用(GNU sed):

    sed 's/[[:digit:]]\+/\n&\n/g;s/^\n\|\n$//g' file
    

    用换行符包围数字,然后删除行首和行尾的所有额外换行符。

    另外两个玩具解决方案:

    sed -r ':a;s/(([^0-9\n])([0-9]+))|(([0-9]+)([^0-9\n]))/\2\5\n\3\6/g;ta'
    

    这很有趣,因为它在替换的 RHS 中使用了 ghost 反向引用。

    sed '/\n/!s/[[:digit:]]\+/\n&\n/g;/^\n/!P;D' file
    

    这会进行一次性替换,然后使用 P D 组合循环遍历由换行符分隔的字符串部分的行。

    【讨论】:

      【解决方案3】:

      我不知道在这种情况下使用tr 是否可行或有效。但是sed 你可以试试:

      echo "1xxx2yyy3zzz"| sed 's/[0-9]/\n&\n/g'| sed '/^\s*$/d'
      

      所以基本上它将每个数字替换为\n number \n。最后一个sed是删除空行(开始和结束)。

      另一种形式

      仅使用一个sed 并且如果您的文本在file 中:

      sed 's/[0-9]/\n&\n/g;s/\(^\n\|\n$\)//' file
      
      • 第一个替换(s/[0-9]/\n&\n/g;) 将任何number 替换为\n number \n
      • 第二次替换 (s/\(^\n\|\n$\)//) 删除开头和结尾中不必要的新行。

      【讨论】:

      • 您可以在单个 sed 中执行此操作,然后您可以看到 stackoverflow.com/a/51580978/5866580 这个。
      • 我明白了,是逆逻辑。
      • /\([0-9]\)/\n\1\n/ = /[0-9]/\n&\n/
      • 谢谢@Ed Morton!,我会修改的。
      【解决方案4】:

      考虑到您的 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.
      

      【讨论】:

      • OP没有说不是数字的字符是字母。您可能应该使用[^0-9] 而不是[a-zA-Z]
      猜你喜欢
      • 2015-09-03
      • 2011-03-10
      • 2020-01-15
      • 2014-10-16
      • 2013-05-02
      • 1970-01-01
      • 1970-01-01
      • 2022-12-22
      • 1970-01-01
      相关资源
      最近更新 更多