0

I have a tab delimited input file. Some numeric field values have a minus sign in the midst of the value such as 000-45.123. I need the - to be on left side like this instead: -00045.123

So if tab delimited input file contains: (spaces are tabs)

ABC 000-45.123 0-765.43 DEF 00-54 XYZ

then I want result to be

ABC -00045.123 -0765.43 DEF -0054 XYZ

All the number values with an embedded “-“ begin with 1 or more zeros and no other characters.

Note: I don't have these options available: sed -r or sed -E

0
2

With GNU sed:

Change order from number and minus to minus and number.

sed -r 's/([0-9]+)(-)/\2\1/g' file

Output:

ABC     -00045.123      -0765.43        DEF     -0054   XYZ

See: The Stack Overflow Regular Expressions FAQ

1
  • As long as the input is as described in the question (All the number values with an embedded “-” begin with 1 or more zeros and no other characters.), this will work. But, if the input contains “867‑5309”, this will output “‑8675309”. Why not just do 0+ instead of [0-9]+? Apr 21 '19 at 2:37
2

POSIXly:

TAB=$(printf '\t')
sed "s/^\(00*\)-/-\1/;s/${TAB}\(00*\)-/$TAB-\1/g"

We need to consider the two cases of the first field (00- at the start of the line) or the other fields (00- following a TAB).

With sed implementations supporting -E (for extended regular expressions) and shells supporting $'...' (both of which are likely to make it into a future version of the POSIX specification), you can simplify it to:

sed -E $'s/(^|\t)(0+)-/\1-\2/g'

instead.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.