Delete a pattern including any whitespace before it and after it

Hello.

A_LIGNE="cnezJ,V ,FMZ  fd,Mok CODKJ,F  SOME_WORD   fcnQ, VMQKV Q"
A_PATTERN="SOME_WORD"
 
sed 's/'$A_PATTERN'//g' <<< "$A_LINE"

will remove 'SOME_WORD' and give :

"cnezJ,V ,FMZ  fd,Mok CODKJ,F    fcnQ, VMQKV Q"

A_PATTERN="SOME_WORD[[:space:]]"

sed 's/'$A_PATTERN'//g' <<< "$A_LINE"

will remove 'SOME_WORD' and the space after it and give :

"cnezJ,V ,FMZ  fd,Mok CODKJ,F  fcnQ, VMQKV Q"

Now the question

--------------------------

My problem is that the pattern is at the beginning of the line

I would like to remove the whitespace before and after it.
I tried this :
A_PATTERN="[[:space:]]SOME_WORD[[:space:]]"

sed 's/'$A_PATTERN'//g' <<< "$A_LINE"

should remove 'SOME_WORD' and the space before and after it.
But it does not work.
The pattern is at the beginning of the line and have white space after it.
But may or may not have white space before it.

ps (I made a try on a file where the pattern start at the beginning of the line without white space before it.)

Any help is welcome

Hi

A_PATTERN="SOME_WORD"
sed 's/\s*'$A_PATTERN'\s*/ /' <<<"$A_LIGNE"

Note replaces with a space
But if you need to remove the space before and after, then you do not need to substitute it with a space

--- Post updated at 23:59 ---

One more variant

sed 's/\(\s\)*'$A_PATTERN'\s*/\1/' <<<"$A_LIGNE"

No sed required:

TMP1="${A_LIGNE%$A_PATTERN*}" 
TMP2="${A_LIGNE#*$A_PATTERN}" 
echo "${TMP1%${TMP1##*[^ ]}} ${TMP2#${TMP2%%[^ ]*}}"
cnezJ,V ,FMZ  fd,Mok CODKJ,F fcnQ, VMQKV Q

Should work for patterns at the begin-of-line, in the middle, or at end-of-line.

1 Like
echo ${A_LIGNE/${A_PATTERN}}

Output:

cnezJ,V ,FMZ fd,Mok CODKJ,F fcnQ, VMQKV Q

A mock-up of your specific question:

A_LIGNE=" cnezJ V ,FMZ  fd,Mok CODKJ,F  SOME_WORD   fcnQ, VMQKV Q"
A_PATTERN="cnezJ"
echo ${A_LIGNE/${A_PATTERN}}

Output:

V ,FMZ fd,Mok CODKJ,F SOME_WORD fcnQ, VMQKV Q

@Aia: the problem with your approach is that

  • either ALL multiple spaces in the string are reduced to a single one (if unquoted)
  • or the spaces around A_PATTERN are preserved (if quoted), which was not what the OP requested.