Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Rename file containing '-' character with sed

A series of file names should be in format:

ABCDEF - XY1234 - FileName.ext

(The middle section is fixed length (2 alpha + 4 numeric), the first and last sections can be longer or shorter than the example. The extension will always be three alphanumeric characters.)

However, some files do not have the hyphens surrounded by spaces:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

EFGHI- WX2345 -FileName.ext
JKLMN-VW3456 - FileName.ext
OPQRS - UV4567- FileName.ext

Is there a way to replace all these combinations "X -X", "X-X", and "X- X" with "X – X" using sed?

(I have tried the pattern of a non-whitespace character followed by a hyphen – '\S\-' as my pattern, but replacing this with a space followed by the hyphen '\ \-' then means I lose the character represented by the '\S'. Had this worked my intention would have been to pass each filename through the three variations to ensure compliance.)

>Solution :

Is there a way to replace all these combinations "X -X", "X-X", and "X- X" with "X – X" using sed?

You may use this sed:

sed -E 's/[[:blank:]]*-[[:blank:]]*/ - /g' file

EFGHI - WX2345 - FileName.ext
JKLMN - VW3456 - FileName.ext
OPQRS - UV4567 - FileName.ext

Breakdown:

  • [[:blank:]]*-[[:blank:]]*: matches - surrounded by 0 or whitespaces on both sides
  • -: replaced that with - surrounded by a single space on both sides

An awk solution would be:

awk -F '[[:blank:]]*-[[:blank:]]*' -v OFS=' - ' '{$1=$1} 1' file

EFGHI - WX2345 - FileName.ext
JKLMN - VW3456 - FileName.ext
OPQRS - UV4567 - FileName.ext

or even this:

awk '{gsub(/[[:blank:]]*-[[:blank:]]*/, " - ")} 1' file
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading