-1

I need a bash script to recursively rename files with blank extensions to append .txt at the end. I found the following script, but I can't figure out how to make it recursive:

#!/bin/sh
for file in *; do
test "${file%.*}" = "$file" && mv "$file" "$file".txt;
done

Thanks.

Thanks.

  • Possible duplicate of [Rename files and directories recursively under ubuntu /bash](http://stackoverflow.com/questions/15012631/rename-files-and-directories-recursively-under-ubuntu-bash) – miken32 Mar 14 '16 at 20:03

2 Answers2

1

You can delegate the heavy lifting to find

$ find . -type f ! -name "*.*" -print0 | xargs -0 -I file mv file file.txt

assumption is without extension means without a period in name.

karakfa
  • 66,216
  • 7
  • 41
  • 56
0

If you don't mind using a recursive function, then you can do it in older Bash versions with:

shopt -s nullglob

function add_extension
{
    local -r dir=$1

    local path base
    for path in "$dir"/* ; do
        base=${path##*/}
        if [[ -f $path && $base != *.* ]] ; then
            mv -- "$path" "$path.txt"
        elif [[ -d $path && ! -L $path ]] ; then
            add_extension "$path"
        fi
    done

    return 0
}

add_extension .

The mv -- is to protect against paths that begin with a hyphen.

pjh
  • 6,388
  • 2
  • 16
  • 17