user3582260
user3582260

Reputation: 37

SED - Replace trailing minus sign

Good Evening,

I'm trying to replace a trailing minus sign with a leading minus sign. The link below was very helpful, but I'm having a hard time dealing with both a comma and period. For example:

Input Data:

|76534|     253,453.86-|       6/4/2012|  56487-56987|
|32567|      36,000.00|        7/8/2012|  45684-4541|
|58531|         400.56-|      10/5/2012|  15232-1254|
|12584|           5.56-|     12/12/2013|  125565-451|

Desired Results (all other columns remain the same):

-253,453.86
  36,000.00
    -400.56
      -5.56

Using sed -r 's/([[:digit:]]+(\,[[:digit:]]+(\.[[:digit:]]+)?))-/-\1/' I've been able to treat numbers with a comma, but I would like to treat all types in one command if possible.

Helpful Link: Replace a trailing minus with leading minus

Upvotes: 0

Views: 1614

Answers (6)

perreal
perreal

Reputation: 98118

A simple solution:

sed 's/\([^ ]*\)\-|/-\1|/' input

Upvotes: 1

Avinash Raj
Avinash Raj

Reputation: 174874

Another one through GNU sed,

$ sed -r 's/^(\|[0-9]+\|)( *?)([^|]*?)(-)(.*)$/\1\2\4\3\5/g' file
|76534|     -253,453.86|       6/4/2012|  56487-56987|
|32567|      36,000.00|        7/8/2012|  45684-4541|
|58531|         -400.56|      10/5/2012|  15232-1254|
|12584|           -5.56|     12/12/2013|  125565-451|

Upvotes: 1

Ed Morton
Ed Morton

Reputation: 204638

$ awk 'BEGIN{FS=OFS="|"} sub(/-$/,"",$3){sub(/[^ ]/,"-&",$3)}1' file
|76534|     -253,453.86|       6/4/2012|  56487-56987|
|32567|      36,000.00|        7/8/2012|  45684-4541|
|58531|         -400.56|      10/5/2012|  15232-1254|
|12584|           -5.56|     12/12/2013|  125565-451|

Upvotes: 1

jaypal singh
jaypal singh

Reputation: 77185

You can do:

$ sed '/-$/{s/-$//;s/[0-9]/-&/;b};s/^/ /' file
-253,453.86
  36,000.00
    -400.56
      -5.56

Updated Answer:

$ awk 'BEGIN{FS=OFS="|"}{for(i=1;i<=NF;i++)if($i~/-$/){sub(/-$/,"",$i);sub(/[0-9]/,"-&",$i)}}1' file
|76534|     -253,453.86|       6/4/2012|  56487-56987|
|32567|      36,000.00|        7/8/2012|  45684-4541|
|58531|         -400.56|      10/5/2012|  15232-1254|
|12584|           -5.56|     12/12/2013|  125565-451|

Upvotes: 1

ooga
ooga

Reputation: 15511

This seems to work with your multi-column data:

sed -r '{s#([0-9][0-9,.]*)-\|#-\1\|#g}'

Upvotes: 1

Floris
Floris

Reputation: 46435

Use [[:digit:],.] to create a character class with numbers, commas and periods. The rest you already know how to do.

sed -r 's/([[:digit:].,])-/-\1/'

Upvotes: 1

Related Questions