-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.)

ilkkachu
  • 138,973

2 Answers2

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)"
Hauke Laging
  • 90,279
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}"
ilkkachu
  • 138,973
JRFerguson
  • 14,740