Renaming multiple files based on their contents

rename

How can I rename all files within a folder with the first word of their content? For example if a.txt contains “Unix is an OS” in its first line then a.txt should be renamed to Unix.txt

Best Answer

Try this:

for f in *.txt; do d="$(head -1 "$f" | awk '{print $1}').txt"; if [ ! -f "$d" ]; then mv "$f" "$d"; else echo "File '$d' already exists! Skiped '$f'"; fi; done

or more long variant (as script):

#!/bin/sh
for f in *.txt; do
    d="$(head -1 "$f" | awk '{print $1}').txt"
    if [ ! -f "$d" ]; then
        mv "$f" "$d"
    else
        echo "File '$d' already exists! Skiped '$f'"
    fi
done

In case when destination file exists this one-liner skips it.

Related Question