Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

change last two digits of a number using sed

I use this command:

sed 's/;\([0-9]*\),\([0-9]*\);/;\1.\2;/g;s/;\(\r\?\)$/\1/' inputfile

to change huge csv-files to my needs (see delete ';' at the end of each line).

Now it happens that in some csv-files there are "fictive dates" like 20000500 that can't be imported to SQL because of the last two zeros (that are not possible for dates).

How can I edit my sed-command to always change the last two digits to 01 in such cases (I mean only if they are 00)?

I tried

sed 's/;\([0-9]*\),\([0-9]*\);/;\1.\2;/g;s/;\([0-9]{6}\)00;/;\101;/g;s/;\(\r\?\)$/\1/' inputfile

but that doesn't work.

like image 810
speendo Avatar asked Mar 15 '11 09:03

speendo


People also ask

How do I change a number using sed?

Find and replace text within a file using sed command Use Stream EDitor (sed) as follows: sed -i 's/old-text/new-text/g' input. txt. The s is the substitute command of sed for find and replace.

What is I flag in sed?

In sed , you can end a command with the flag "/i" (for example, see this other question). This seems to say "more sed commands coming," or something like that, so you can split sed commands in a script.

How do you end a sed?

(quit) Exit sed without processing any more commands or input. (quit) This command is the same as q , but will not print the contents of pattern space.


1 Answers

I think {6} is an extended regular expression. So you either have to use sed -r or you change your regexp to s/;\([0-9][0-9][0-9][0-9][0-9][0-9]\)00;/;\101;/g.

If you want to use extended regular expressions, do:

sed -r 's/;([0-9]{6})00;/;\101;/g'

I.e.: you have to remove the backslashes from parens.

Edit: Regarding to Dennis Williamson's comment it's also possible to use regular regexps by escaping the curly braces:

sed 's/;\([0-9]\{6\}\)00;/;\101;/g'
like image 165
bmk Avatar answered Sep 23 '22 01:09

bmk