Ubuntu – Renaming files to add a suffix

bashbatch-rename

I need a command to rename all files in the current working directory, in a way that the new filename will be the same as the old, but including a suffix corresponding to the number of lines of the original files (e.g. if the file f has 10 lines then it should be renamed to f_10).

Here's my (non-working) attempt:

 linenum=$(wc -l); find * -type f | grep -v sh | rename 's/^/ec/'*

Best Answer

How about:

for f in *; do mv "$f" "$f"_$(wc -l < "$f"); done

For example:

$ wc -l *
 10 file1
 40 file2
100 file3
$ ls
file1_10  file2_40  file3_100

If you want to keep extensions (if present), use this instead:

for f in *; do 
    ext=""; 
    [[ $f =~ \. ]] && ext="."${f#*.}; 
    mv "$f" "${f%%.*}"_$(wc -l < "$f")$ext; 
done
Related Question