I have a input in which delimeter is <;| like given below:-

1-<;|3-Text <;|3.13-<;|0.28-<;|9
0.12-<;|2-Text <;|3.99-<;|4.11-<;|6
0.13-<;|3-Text <;|8.13-<;|3.98-<;|3

My expected output should be:-

-1<;|3-Text <;|-3.13<;|-0.28<;|9 
-0.12<;|2-Text <;|-3.99<;|-4.11<;|6
-0.13<;|3-Text <;|-8.13<;|-3.98<;|3

Here, I would like to bring the minus sign in front of only integer or decimal value and not for text field. The columns are not fixed and can be of any order. I am trying to use sed command but not successful with it. Please help me in this scenario.

  • sed 's/\([0-9.]\+\)-</-\1</g' – Costas Dec 16 '14 at 12:05
  • Your examples include: 1-<;|3-Text <;|. Will Text always follow the number? Or, could your input contain 1-<;|Text 3-<;|? – John1024 Dec 16 '14 at 12:10
  • The input can contain Text 3- or 3- Anytext or 3-Anytext. – Shraddha K Dec 16 '14 at 12:46

With GNU sed:

sed 's/\([[:digit:]]\+\)\(\.[[:digit:]]*\)\{0,1\}-\(\W\)/-\1\2\3/g'

GNU version of sed is needed in order to match "non-word" character after - with \W. You can simulate this with non-gnu version using [^a-zA-Z0-9_].

If - should not be changed also in case it precedes space than just add space to previous pattern, so:

sed 's/\([[:digit:]]\+\)\(\.[[:digit:]]*\)\{0,1\}-\([^a-zA-Z0-9_ ]\)/-\1\2\3/g'
  • With non-gnu, you should be able to use [^[:alnum:]_] – glenn jackman Dec 16 '14 at 13:02
  • Can you please share the actual usage of this in the command. – Shraddha K Dec 16 '14 at 13:18
  • Thanks sed 's/([[:digit:]]+)(.[[:digit:]]*){0,1}-([^a-zA-Z0-9_ ])/-\1\2\3/g' is working. But the only case this fails is when there is only a whitespace behind the minus sign for other numeric fields it does not swap. For eg:- echo "0.11- <;|3- Test <;|3.13-<;|" | sed 's/([[:digit:]]+)(.[[:digit:]]*){0,1}-([^a-zA-Z0-9_ ])/-\1\2\3/g' output is 0.11- <;|3- Test <;|-3.13<;| – Shraddha K Dec 16 '14 at 13:50
  • So perhaps better match delimiter <;| exactly after minus and any number of spaces: sed 's/\([[:digit:]]\+\)\(\.[[:digit:]]*\)\{0,1\}-\(\s*<;|\)/-\1\2\3/g' – jimmij Dec 16 '14 at 14:09

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.