Skip to content
Advertisement

How to identify directory paths within multi-line string, replace with references to own file content, in Bash?

Given a bash variable containing the following multi-line string representing *nix paths:

/some/app/path/dir1
/some/app/path/somefile1.txt
/some/other/app/path/somefile2.txt
/some/random/app/path/dir2

I’d like to be able to identify all directories (dir1 & dir2, for example) and to replace these directory path lines with the paths of the files below them. There should be no directory references in the final output, thus:

#Nodirectory references, just files.
/some/app/path/dir1/dir3/file1.xml
/some/app/path/dir1/dir3/file2.doc
/some/app/path/somefile1.txt
/some/other/app/path/somefile2.txt
/some/random/app/path/dir2/file3.png
/some/random/app/path/dir2/dir4/file4.txt

I’m not sure exactly how to iterate over the lines and remove/replace the directories, how could I do this?

I’m assuming the use of ‘if’ and various operators to identify directories, and ‘find /my/dir -type f’, to actually find the files.

I’m using Mac OSX 10.10 (Yosemite).

Advertisement

Answer

Test if the name is a directory. If it is, call find, otherwise just echo it as it is.

echo "$variable" | 
    while IFS= read -r name
    do
        if [[ -d $name ]]
        then 
            find "$name" -type f -print
        else
            echo "$name"
        fi
    done

Instead of piping echo "$variable", you can also use a here-string:

while IFS= read -r name
do
    if [[ -d $name ]]
    then 
        find "$name" -type f -print
    else
        echo "$name"
    fi
done <<<"$variable"
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement