Replace all but a set of characters in a file with newline

5,045

Solution 1

This is a classic tr use case, so the simplest way is:

tr -cs '[:digit:].' '[\n*]' < input > output

The [:digit:]. argument specifies the characters to match (digits and dot). The [\n*] specifies the characters to replace with (replace everything with newline). The -c option inverts the first argument since we want everything except digits and dot. The -s squeezes consecutive newlines from the second string into one.

Solution 2

grep can do it:

grep -o '[0-9.]\+'
Share:
5,045

Related videos on Youtube

yael
Author by

yael

Updated on September 18, 2022

Comments

  • yael
    yael over 1 year

    how to delete all characters in file except numbers and "." , each word (numbers/dot) should be in new line in file see example2

    • the solution can be with sed or awk or ksh syntax

    remark - the solution must be according to the example 2

    example 1

    file before edit

      192.0.22.1++0.1
      e32)5.500.5.5*kjcdr
      ##@$1.1.1.1+++jmjh
      1.1.1.1333
      33331.1.1.1
      @5.5.5.??????
      ~3de.ede5.5.5.5
      1.1.1.13444r54
      192.9.30.174
      &&^#%5.5.5.5
      :5.5.5.5@%%^^&*
      :5.5.5.5:
      **22.22.22.22
      172.78.0.1()*5.4.3.277
      3.3.3ki.3.
    

    example 2 of file after delete all characters except numbers and "." charter , each new word will be in new line

      192.0.22.1
      0.1
      32 5.500.5.5
      1.1.1.1
      1.1.1.1333
      33331.1.1.1
      5.5.5.
      .
      5.5.5.5
      1.1.1.13444
      54
      192.9.30.174
      5.5.5.5
      5.5.5.5
      5.5.5.5
      22.22.22.22
      172.78.0.1 
      5.4.3.277
      3.3.3 .3.
    
    • jw013
      jw013 over 11 years
      Your sample output is a bit inconsistent. Why are 32 and 5.500.5.5 both on line 3? Why is there no 3 (from 3de) between the lines for 5.5.5. and .? Why are 3.3.3 and .3. both on the last line?
    • Angel Todorov
      Angel Todorov over 11 years
      This looks an awful lot like this question on ServerFault -- did you not get a good answer there?
  • Stéphane Chazelas
    Stéphane Chazelas over 11 years
    Note that \n above in the sed command example is not standard. The standard syntax to specify a newline character in the RHS of a s command is with a backslash followed by a new line character.