sed + how to delete the second character "." from the line

5,990

Solution 1

Simply add N to the end of the command for it to match the Nth match, like this:

uname -r | sed 's/\./ /2'

What do you need it for though?


From the info page on sed:

The `s' command can be followed by zero or more of the following FLAGS:

g

Apply the replacement to _all_ matches to the REGEXP, not just the first.

NUMBER

Only replace the NUMBERth match of the REGEXP.

Solution 2

Here are a few ways to remove the second . from a line of a file (they will affect all lines of the file):

  1. sed. You already have what is probably the best way, but here's another:

    sed 's/\([^.]*\.[^.]*\)\./\1 /' file 
    

    This will look for the longest stretch of non-. ([^.]*), then a . (\.), then the next stretch of non-. and finally a . (\.). The parentheses capture the patterns so we can refer to it as \1. Therefore, the command above will just delete the second . and replace it with a space.

    If you have GNU sed (default on Linux), you can simplify to:

    sed -r 's/([^.]*\.[^.]*)\./\1 /' file 
    
  2. Perl

    perl -pe 's/([^.]*\.[^.]*)\./\1 /' file 
    

    or

    perl -F'\.' -ane 'print "$F[0].$F[1] ", join ".", @F[2..$#F]' file 
    
  3. awk (I'm sure there's a better way)

    awk -F. '{printf "%s.%s ",$1,$2; for(i=3;i<NF;i++){printf "%s.",$(i); }print $NF}' file 
    
Share:
5,990

Related videos on Youtube

maihabunash
Author by

maihabunash

I am 17 years old and love to develop

Updated on September 18, 2022

Comments

  • maihabunash
    maihabunash over 1 year

    how to delete the second character "." from the line

    what I have is this ( but its remove the first "." from output

    uname -r | sed s'/\./ /'
    
    2 6.18-164.2.1.el5PAE
    

    while I need the following output

    2.6 18-164.2.1.el5PAE
    
    • terdon
      terdon over 9 years
      Please also show us the input. I can extrapolate from the output and assume that your input is 2.6.18-164.2.1.el5PAE but including it would make the question clearer.
  • maihabunash
    maihabunash over 9 years
    I need only the first number from uname -r ( 2.6 ) all other numbers are non relevant anyway thx on your good answer