I am trying to crate a folder with the label and uuid of a media device plugged in as its name, on another flash drive which I am using to log. I have the following code:

MD=`lsblk -I 8 -o label,uuid -n|sed -e '/^$/ d' -e '/^$LOGDEVICELABEL.*$/ d'`

The problem is that the value pf the variable $MD has a space in the beginning which I cannot get rid of. That space causes mkdir to treat /media/$LOGDEVICELABEL/Log/ and $MDas two separate arguements.

I tried:

MDLOGDIR=`sed 's/ // g' <<</media/$LOGDEVICELABEL/Log/$MD` 

Which only removes the space between the UUID and the Label (which is also necessary) but does not remove the space between /media/$LOGDEVICELABEL/Log/ and $MD.


One thing I'll do is use echo to strip unwanted whitespace. In this context, it's important to omit any quotes:

MD=$(lsblk -I 8 -o label,uuid -n|sed -e '/^$/ d' -e '/^$LOGDEVICELABEL.*$/ d')
MD=$(echo $MD) # <-- This line

The shell invokes the echo command and supplies it with a series of tokens, and the echo command prints those tokens separated by a space character. This has the effect of (1) skipping leading and trailing whitespace and (2) converting one or more whitespace characters between tokens to a single space.

My use of $(...) instead of the back-tick version in this context is equivalent to the back-tick version. Generally I find this version easier to read. It also has the nice benefit that it can be nested ($(...$(...))) where the back-tick version cannot.

  • Can you explain why that worked vs what I had tried? Also, what is the advantage of $() notation that you used vs the `` that I used. Thanks – novice Oct 4 '18 at 16:28
  • Why doesn't sed take care of the trailing whitespace (or RudiC's answer) work? Is it a different type of whitespace? – novice Oct 4 '18 at 17:02
  • To be clear, I'm not claiming that others' answers won't work. The answer that I provided here is one possible solution. – Andy Dalton Oct 4 '18 at 17:04
  • I tried them, they don't work. Do you know why? – novice Oct 4 '18 at 17:06
  • It could be the number of whitespace characters; the lsblk output is preceeded by more than one space. – Andy Dalton Oct 4 '18 at 17:11

Why not use "parameter expansion" like


or extend the sed like

s /^ //
  • Have you tried this? Neither worked for me. – novice Oct 4 '18 at 16:56
  • MD=" Josef" echo ">$MD<" > Josef< echo ">${MD# }<" >Josef< echo ">${MD/ }<" >Josef< – RudiC Oct 4 '18 at 17:50

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.