I have the following

"/x/x y/asfas/g.pdf          " "fdfdf
"/x/y/yy    y/d.doc    " "fdfdf

I want to remove the spaces between the extension and the " ONLY

when I used tr to remove trailing space it removes the spaces in between that are more than 1 space (ex: yy y becomes yy y)

  • 1
    Will that always be the first whitespace before the second " character? – terdon Jun 20 '17 at 11:42

GNU sed approach:

sed 's/\([^.]*\.[^."[:space:]]*\)[[:space:]]\+"/\1"/' file

  • \([^.]*\.[^."[:space:]]*\) - the 1st captured group containing hypothetical filename with extension

  • [[:space:]]\+" - ensures at least one space between extension and "


You could do:

sed 's/\(\.[^"[:blank:]]*\)[[:blank:]]*"/\1"/g'

That is remove the sequences of blanks that follow . followed by a sequence of non-blank-nor-" characters and are followed by a "

To remove the blanks before every other double quote character on each line, you could do something like:

sed 's/[[:blank:]]*"/"&/g

That is:

  1. Insert an extra " before each <blanks>"
  2. Change all the <X>"<blanks>"<Y>"<blanks>" to <X>"<blanks>"<Y>""
  3. Remove every other " to undo the insertions in 1

Or in a more straightforward manner with awk:

awk -F \" -v OFS=\" '
    for (i = 2; i <= NF; i += 2 )
      sub(/[[:blank:]]*$/, "", $i)

Note that tr wouldn't squeeze characters unless you use the -s option. More likely you forgot to quote a parameter expansion or command substitution that contained the output of tr.

In any case, tr can't be used for that task. It's just a transliteration tool. All it could do is translate/delete/squeeze all space characters. It cannot translate/delete/squeeze only some space characters.


Use GNU sed. Search for one or more spaces, followed by a double quote. Replace that with a double quote:

sed -i -e 's/ \+"/"/' file

or like this, at your option:

sed -i -e 's/[[:space:]]\+"/"/' file
  • That would change "foo.bar" "baz" to "foo.bar""baz" though – Stéphane Chazelas Jun 20 '17 at 11:13
  • @StéphaneChazelas Yes, if that pattern would occur. There is not that many samples in the question, so it is not clear to say. – hschou Jun 20 '17 at 11:36

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.