-2

I need to write a function that does the following: the function receives file names with this format *.station

Between the words might be multiple spaces, I want to remove the extra spaces between the words and leave only one.

For example (1): aa__________a____aa _____________ ssd________.station, needs to be changed to aa_a_aa_ssd.station

(2): aa______________a.station needs to be written as: aa_a.station

(The underscores (_) signify spaces in the above.)

  • i am not allowed to use tr unfortunately – evgniy tayarov Aug 22 '17 at 17:50
  • 3
    Why are you "not allowed" to use tr? Is this homework? – Wildcard Aug 22 '17 at 19:50
1
shopt -s extglob
file="aa     a       a.station"
echo mv "$file" "${file// +( )/ }"

An alternative would be a loop with

"${file//  / }"

until there are only single spaces left:

file="a                      a"

last_run=""
new="$file"
while [ "$last_run" != "$new" ]; do
        last_run="$new"
        new="${last_run//  / }"
done

echo mv "$file" "$new"

Or with word splitting:

IFS=" "
mv "$file" "$(echo $file)"
0
#!/bin/bash
file="aa     a       a.station"
read -r -a myarray <<< "$file"
printf  "${myarray[*]}"

This reads a string into an array, splitting on the standard IFS characters (space, tab, newline). The entire array, each element, now with single delimiters, is then printed.

You can also leverage xargs:

#!/bin/bash
file="aa     a       a.station"
newfile=$(echo $file|xargs)
printf  "${newfile}"
  • Why the effort with read? myarray=($file) And IFS should be set to space only. – Hauke Laging Aug 22 '17 at 19:43

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.