Ankur Agarwal
Ankur Agarwal

Reputation: 24758

Delete _ and - characters using sed

I am trying to convert 2015-06-03_18-05-30 to 20150603180530 using sed.

I have this:

$ var='2015-06-03_18-05-30'
$ echo $var | sed 's/\-\|\_//g'
$ echo $var | sed 's/-|_//g'

None of these are working. Why is the alternation not working?

Upvotes: 1

Views: 130

Answers (5)

NeronLeVelu
NeronLeVelu

Reputation: 10039

sed 's/[^[:digit:]]//g' YourFile

Could you tell me what failed on echo $var | sed 's/\-\|\_//g', it works here (even if escapping - and _ are not needed and assuming you use a GNU sed due to \| that only work in this enhanced version of sed)

Upvotes: 0

Charles Duffy
Charles Duffy

Reputation: 295373

As long as your script has a #!/bin/bash (or ksh, or zsh) shebang, don't use sed or tr: Your shell can do this built-in without the (comparatively large) overhead of launching any external tool:

var='2015-06-03_18-05-30'
echo "${var//[-_]/}"

That said, if you really want to use sed, the GNU extension -r enables ERE syntax:

$ sed -r -e 's/-|_//g' <<<'2015-06-03_18-05-30'
20150603180530

See http://www.regular-expressions.info/posix.html for a discussion of differences between BRE (default for sed) and ERE. That page notes, in discussing ERE extensions:

Alternation is supported through the usual vertical bar |.


If you want to work on POSIX platforms -- with /bin/sh rather than bash, and no GNU extensions -- then reformulate your regex to use a character class (and, to avoid platform-dependent compatibility issues with echo[1], use printf instead):

printf '%s\n' "$var" | sed 's/[-_]//g'

[1] - See the "APPLICATION USAGE" section of that link, in particular.

Upvotes: 4

josifoski
josifoski

Reputation: 1726

Easy:

sed 's/[-_]//g' 

The character class [-_] matches of the characters from the set.

Upvotes: 0

geckon
geckon

Reputation: 8754

I know you asked for a solution using sed, but I offer an alternative in tr:

$ var='2015-06-03_18-05-30'
$ echo $var | tr -d '_-'
20150603180530

tr should be a little faster.

Explained:

  • tr stands for translate and it can be used to replace certain characters with another ones.
  • -d option stands for delete and it removes the specified characters instead of replacing them.
  • '_-' specifies the set of characters to be removed (can also be specified as '\-_' but you need to escape the - there because it's considered another option otherwise).

Upvotes: 1

Tim Pote
Tim Pote

Reputation: 28029

Something like this ought to do.

sed 's/[-_]//g'

This reads as:

  1. s: Search
  2. /[-_]/: for any single character matching - or _
  3. //: replace it with nothing
  4. g: and do that for every character in the line

Sed operates on every line by default, so this covers every instance in the file/string.

Upvotes: 2

Related Questions