Search code examples
sedregex-group

Is there any way to match a string with only one character into character 'X' in sed?


I want to match all strings that have only one single character (including having with + or -) to turn into X but I get this output instead whenever I run it:

Xone     X
Xtwo     X
Xthree   X

Here's the file that I'm supposed to run with:

Cone      A-
Ctwo      D
Cthree    C+

Here's the code I've been working on:

code.sed

#!/bin/sed
s/[A-D][+-]/X/
s/[A-D]/X/

Desired output:

Cone      X
Ctwo      X
Cthree    X

Solution

  • Using a GNU sed, you can use

     sed -E 's/\b[[:upper:]]\b[+-]?/X/g'
    

    Details:

    • -E enables POSIX ERE syntax
    • \b - a word boundary
    • [[:upper:]] - an uppercase letter
    • \b - a word boundary
    • [+-]? - an optional + or -.

    See an online demo:

    s='Cone      A-
    Ctwo      D
    Cthree    C+'
    sed -E 's/\b[[:upper:]]\b[+-]?/X/g' <<< "$s"
    

    Output:

    Cone      X
    Ctwo      X
    Cthree    X