I am trying to remove white spaces from each variable string. I tried with below command but no use.

a="HARISH , SAM"
echo $a|sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//'

closed as unclear what you're asking by Kusalananda, Jeff Schaller, G-Man, RalfFriedl, JigglyNaga Dec 6 at 10:08

Please clarify your specific problem or add additional details to highlight exactly what you need. As it's currently written, it’s hard to tell exactly what you're asking. See the How to Ask page for help clarifying this question. If this question can be reworded to fit the rules in the help center, please edit the question.

  • 2
    your desired output? – msp9011 Dec 5 at 13:11
  • Are there other spaces, that you want to keep (for example between words)? – sudodus Dec 5 at 13:22
  • What if the person's name is HARISH , SAM MIDDLENAME? – Jeff Schaller Dec 5 at 13:39
  • 2
    Your string does not have any whitespace at the start or end to trim. This question is unclear. – Kusalananda Dec 5 at 15:50
up vote 0 down vote accepted

Try this,

 echo $a | sed -e 's/ //g'

you can also try if you have first name and last name

echo $a | sed -e 's/ , /,/g'
  • It is working fine. Thank you. – Harish a Dec 5 at 13:34
  • Above command supports if we have spaces begining, ending and between the string, but if we don't remove between strings like Frist and Second Name then it won't support. – Harish a Dec 5 at 13:37
  • 1
    It is working. Thanks again. – Harish a Dec 5 at 13:44

Assuming with "variable string in Linux" you mean a shell variable, why not use shell's "Parameter Expansion", "Pattern Substitution"? Like

$ a="HARISH , SAM"
$ echo ${a// }
HARISH,SAM
  • this would remove the space between the first name and surname. – msp9011 Dec 5 at 15:09

Not the answer you're looking for? Browse other questions tagged or ask your own question.