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

Viewed 32

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
2 Answers

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

With your shown samples, could you please try following, written and tested in GNU awk.

awk '{gsub(/\<[A-Z]\>[-+]?/,"X")} 1' Input_file

Explanation: Simply globally substituting capital letter(placing word boundary before it) followed by optional + or - with X in current line.

Related