I am running two Linux commands and I want to put the resulting values together in a filename with no spaces and a dot separating the two values. So far, I've got this:

pid=`sudo dmidecode -s system-product-name`
vid=`sudo dmidecode -s system-version`
# cleanup spaces in $pid and $vid

How can I clean up the spaces in the two variables?


You can use bash "Pattern substitution" (search for that string in the man page for details).

filename=${pid// /}.${vid// /}.tar.gz

The double slash means replace all occurrences of the pattern. The space between the double slash and the next slash is the pattern. The replacement pattern is after the last slash, which in this case is empty. You can remove the final slash, but I prefer it for clarity as it brackets the space.


You can use sed:

pid=$(sudo dmidecode -s system-product-name | sed 's/  *//g')
  • Why two spaces in the sed pattern? Is that a posix thing? – Peter.O Aug 24 '11 at 8:01
  • 1
    @fred: ' *' (one space) means also zero spaces, ' *' (two spaces) instead is equivalent to ' \+' (one space) and match at least a space (as @Caleb pointed out in a recent comment to another answer). * metachar is POSIX basic regex, \+ is not accepted from all sed implementations. – enzotib Aug 24 '11 at 8:05
  • 1
    Also, tr -d ' ' – glenn jackman Aug 24 '11 at 13:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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