-1

This is the output I have now. How can I get from Input to Output?

Input:

1.2.3.4.5
2.3.4.5.6

Output:

1.2.3.4-5
2.3.4.5-6

Bonus: I have the other 80% of the script done but this is my ideal output. Is there a super simple way to do it?

Input:

1.2.3.4-1.2.3.10

Output:

1.2.3.4-10
1
  • 1
    Bonus part is entirely separate case, so should belong in a separate question Jun 19, 2017 at 17:08

3 Answers 3

1

With awk:

awk -F '[-.]' '{printf "%s.%s.%s.%s-%s\n", $1, $2, $3, $4, $NF}'

Since it looks like you want fields 1-4 and the last field from input separated by either . or -, and the output formatted with all but the last field separated by ..

More concisely:

awk -F '[-.]' -v OFS=. '{$4 = $4"-"$NF; NF=4}1'
  • Add the last field to the fourth field and set the number of fields to 4.
0

First part:

$ sed 's/\./-/4' file.txt

Which replaces the 4th occurrence of . with a -.


For your Bonus section:

sed -r 's/(.*)-.*\.(.*)$/\1-\2/' file.txt

input:

1.2.3.4-1.2.3.10

output:

1.2.3.4-10
0

We can use grouping with greedy match with sed like so:

$ sed -r 's/(.*)\.(.*)$/\1-\2/' input.txt                                
1.2.3.4-5
2.3.4.5-6

Same idea for perl:

$ perl -pe's/(.*)\.(.*)$/\1-\2/' input.txt                               
1.2.3.4-5
2.3.4.5-6

But we can play around with . as column separator in awk:

$ awk -F '.' 'BEGIN{OFS=FS}{$NF=-$NF;sub(/\.-/,"-");print}' input.txt        
1.2.3.4-5
2.3.4.5-6

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .