Home > Back-end >  How to replace the position of a directory containing spaces
How to replace the position of a directory containing spaces

Time:11-24

I made two pipelines; this, x="$(ls -1p | grep "/$" | tr -d "/")" get all the sub directories from the working directory, and this, y="$(ls -1p | grep "/$"| grep \ | tr -d "/")" gets the sub directories that contain spaces in the working directory.

So now what I've trying to do is to replace the position of the directory that contains spaces and puts it at the very top, ie., say below are my sub dirs:

Dir1

Dir2

Dir 3

Now Dir 3 goes to the top

Dir 3

Dir1

Dir1

for I in $x; do
    for X in $y; do
        if [[ $I == $X ]];then
            sed "/"$X"/d" "$I"
        fi
    done
    echo "$I"
done

Above is my loop to do that task. It prints all the sub dirs that contains no spaces but prints it as:

Dir1
Dir2
sed: Dir: No such file or directory
Dir
sed: 3: No such file or directory
3

If anyone can help out that will be greatly appreciated

CodePudding user response:

If you prefer for loop to the find command, how about:

#!/bin/bash

# 1st loop to print the dirnames containing space character
for d in */; do                         # loops over subdirectories under current directory
    if [[ $d =~ [[:space:]] ]]; then    # if the dirname contains a space character
        echo "${d%/}"                   # then print the name removing the trailing slash
    fi
done

# 2nd loop to print the dirnames without space character
for d in */; do
    if [[ ! $d =~ [[:space:]] ]]; then  # if the dirname does not contain a space character
        echo "${d%/}"
    fi
done

Output with the provided example:

Dir 3
Dir1
Dir2

CodePudding user response:

Using GNU find:

find . -mindepth 1 -type d -name '*[[:space:]]*'       # spaces
find . -mindepth 1 -type d -regex '.*/[^/[:space:]] $' # no spaces

This is recursive.

  • Related