Remove leading and trailing whitespace directories

The problem is that Mac OS X lets folders get names like " Foo Bar /".

This is what I could fix on my own and it works for most of the problems.

for d in */ ; do echo "$d" | xargs done

Result: "Foo Bar /".

The only problem it leaves that last space between the directory name and the slash.

Can someone help get rid of that last space?

-------------Problems Reply------------

Try this for a bash-only approach:

dir="some dir /"
fixed=${dir/ \///}
echo $fixed
some dir/

Bash string manipulation:


${string#substring} - remove shortest substring match from beginning

${string##substring} - remove longest substring match from beginning


${string%substring} - remove shortest matching substring from tail

${string%%substring} - remove longest matching substring from tail


${string/substring/replacement} - replace first match of substring

${string//substring/greplacement} - replace all matches of substring

${string/#substring/replacement} - replace substring at front of string

${string/%substring/replacement} - replace substring at tail of string

The problem is that Mac OS X lets folders get names like " Foo Bar /"

This is a Unix/BASH issue too. All characters except NUL and forward slash are valid characters in file names. This includes control characters like backspace and UTF8 characters.

You can use ${WORD%%filter} and ${WORD##filter} to help remove the extra spaces on the front and end of files. You might also want to substitute white space with an underscore character. Unix shell scripts usually work better if file names don't contain white space:

for file in *
new_file=$(tr -s " "<<<"$file")
mv "$file" "$new_file"

The tr -s " " uses the tr command to squeeze spaces out of the file name. This also squeezes beginning and ending spaces on Mac OS X too. This doesn't remove tab characters or NLs (although they could be added to the string.

The for file in * does assign the file names correctly to $file. The <<< is a Bashism to allow you to redirect a string as STDIN. This is good because tr only works with STDIN. The $(...) tells Bash to take the output of that command and to interpolate it into the command line.

This is a fairly simply script and may choke on other file names. I suggest you try it like this:

for file in *
new_file=$(tr -s " "<<<"$file")
echo "mv '$file' '$new_file' >> output.txt

Then, you can examine output.txt to verify that the mv command will work. Once you've verifies output.txt, you can use it as a bash script:

$ bash output.txt

That will then run the mv commands you've saved in output.txt.

What about using sed like this:

name=" Foo Bar /"
echo "$name" | sed 's/^\s*\(.*\)\s*$/\1/g' | tr -s ' '

The sed expression removes all spaces before and after your name, while tr squeezes them to a maximum of one.

Category:bash Views:0 Time:2017-09-11

Related post

  • How can I remove leading and trailing whitespaces from array elements? 2010-07-07

    I have an array that contains string which may contain whitespaces appended to the end. I need to remove those spaces using perl script. my array will look like this @array = ("shayam "," Ram "," 24.0 "); I need the output as @array = ("shayam","Ram"

  • How to remove leading and trailing whitespace from the string in Java? 2012-02-02

    I want to remove the leading and trailing whitespace from string: String s = " Hello World "; I want the result to be like: s == "Hello world"; --------------Solutions------------- s.trim() see String#trim() Without any internal method, use regex lik

  • How to remove leading and trailing whitespaces? 2012-02-07

    I'm using awk '{gsub(/^[ \t]+|[ \t]+$/,""); print;}' in.txt > out.txt to remove both leading and trailing whitespaces. The problem is the output file actually has trailing whitespaces! All lines are of the same length - they are right padded with

  • How to trim leading and trailing whitespace in R? 2010-02-14

    I am having some troubles with leading and trailing whitespace in a data.frame. Eg I like to take a look at a specific row in a data.frame based on a certain condition: > myDummy[myDummy$country == c("Austria"),c(1,2,3:7,19)] [1] codeHelper countr

  • Removing leading and trailing spaces from a string 2009-11-25

    How to remove spaces from a string object in C++. For example, how to remove leading and trailing spaces from the below string object. //Original string: " This is a sample string " //Desired string: "This is a sample string" The string class, as far

  • Perl: function to trim string leading and trailing whitespace 2011-01-04

    Is there a built-in function to trim leading and trailing whitespace such that trim(" hello world ") eq "hello world"? --------------Solutions------------- This is available in String::Util with the trim method: use String::Util 'trim'; my $str = " h

  • Boost spirit parsing string with leading and trailing whitespace 2014-07-21

    I am still new to Boost spirit. I am trying to parse a string with possible lead and trailing whitespace and intermediate whitespace. I want to do the following with the string Remove any trailing and leading whitespace Limit the in-between word spac

  • Can you preserve leading and trailing whitespace in XML? 2009-01-05

    How does one tell the XML parser to honor leading and trailing whitespace? Dim xml: Set xml = CreateObject("MSXML2.DOMDocument") xml.async = False xml.loadxml "<xml>1 2</xml>" wscript.echo len(xml.documentelement.text) Above prints out 3.

  • How can I remove leading and trailing quotes in SQL Server? 2009-06-30

    I have a table in a SQL Server database with an NTEXT column. This column may contain data that is enclosed with double quotes. When I query for this column, I want to remove these leading and trailing quotes. For example: "this is a test message" sh

  • MATLAB - Remove Leading and Trailing Zeros From a Vector 2011-03-30

    I have a wavelet function with leading and trailing zeros. I would like to strip all the zeros which occur before or after the wavelet. However, I would not like to remove any zeros within the wavelet itself. To simplify, let's say I have the followi

  • How to remove leading and trailing white spaces from a given html string? 2012-04-05

    I have the following html string. What would be sample code in JavaScript to remove leading and trailing white spaces from this string? <p>&nbsp;&nbsp;</p> <div>&nbsp;</div> Trimming using JavaScript<br />

  • C# Regular Expression: Remove leading and trailing double quotes (") 2010-07-19

    If I have a string like below... what is the regular expression to remove the (optional) leading and trailing double quotes? For extra credit, can it also remove any optional white space outside of the quotes: string input = "\"quoted string\"" ->

  • Remove leading and trailing brackets in a String 2011-12-26

    In Java, I want to get rid of the leading and trailing brackets in a String. Given input: "[ hello, char[]={a,b,c} ... bye ]" How can I produce the output of " hello, char[]={a,b,c} ... bye " only the leading [ and trailing ] is removed... How can I

  • how to remove leading and trailing non-alphabetic characters in ruby 2010-06-29

    I want to remove any leading and trailing non-alphabetic character in my string. for eg. ":----- pt-br:-" , i want "pt-br" Thanks --------------Solutions------------- result = subject.gsub(/\A[\d_\W]+|[\d_\W]+\Z/, '') will remove non-letters from the

  • Shell script: Removing leading and trailing spaces between fields in a pipe delimited file 2011-07-29

    I have a pipe delimited file as below 1 |Mike | 2000| 2| 2 |Peter | 4000| 2| ..... ... .... and so on. I want to remove the leading and trailing spaces between fields. It should look like as below 1|Mike|2000|2| 2|Peter|4000|2| Is there any way in sh

  • remove leading and trailing slash (/)- Python 2012-05-02

    I am using request.path to return current url in django, it is returning /get/category. I need it as get/category (without leading and trailing slash). Any idea? --------------Solutions------------- >>> "/get/category".strip("/") 'get/catego

  • Replace only leading and trailing whitespace with underscore using regex in c# 2010-12-28

    I want to replace only leading and trailing white space of a string by number of underscore. Input String " New Folder " (Notes: There is one white space at front and two white spaces at the end of this string) Output My desire output string "_New Fo

  • Problem in using Sed to remove leading and trailing spaces 2009-11-20

    I am using the following code to remove both leading and tailing spaces from all lines of a file A.txt sed 's/^[ \t]*//;s/[ \t]*$//' ./A.txt > ./B.txt The problem occurs on the lines where there is a t in the beginning or at the end. So say for ex

  • Remove leading and tailing whitespaces from filename 2015-03-01

    I need a little help with a bash command in Ubuntu 14.04. I have a folder with many subfolders and some of the folder- and filenames have leading or tailing whitespaces. I like to rename these folders and files, but with the same filename, just witho

  • How can I match quoted text excluding leading and trailing whitespaces? 2009-01-14

    I.e. the match of He said, "For my part, it was Greek to me. " should be For my part, it was Greek to me. Without the trailing space. I've tried \"\s*([^\"]*)\s*\" but it's always matching trailing whitespaces in the group. --------------Solutions---

  • How to remove leading and trailing spaces from strings in a Python list 2010-09-01

    i have a list: row=['hi', 'there', 'how', ...........'some stuff is here are ','you'] as you can see row[8]='some stuff is here are ' if the last character is a space i would like to get everything except for the last character like this: if row[8][l

  • How Do I Trim Leading and Trailing Quote from MySQL Row? 2011-07-16

    I have a MySQL table that I have imported from a CSV file. In this process, a bunch of the entries have quote marks leading and trailing the entry of several data rows. For example the the table 'example_table' I have a row called 'title.' Some of th

  • Is it good practice to trim whitespace (leading and trailing) when selecting/inserting/updating table field data? 2009-07-18

    Presuming that the spaces are not important in a field's data, is it good practice to trim off the spaces when inserting, updating or selecting data from the table ? I imagine different databases implement handling of spaces differently, so to avoid

  • Best algorithm to strip leading and trailing spaces in C 2008-12-09

    What is the best approach in stripping leading and trailing spaces in C? --------------Solutions------------- You can do this entirely in place. void stripLeadingAndTrailingSpaces(char* string){ assert(string); /* First remove leading spaces */ const

Copyright (C), All Rights Reserved.

processed in 0.176 (s). 11 q(s)