In a for loop, how do I echo only the current file on a single(updating) line instead of EVERY file which will produce a list?

1

1

My first question on this stackexchange, and I am sure there will be more as I venture farther into the world of what is Linux...

I have a for-loop in a shell-script that batch renames all files to a substring (the last n characters) of its original name.

It will echo every iteration on a new line to eventually produce a list of all files but how do I keep that echo on a single/updating line so it doesn't produce this (sometimes large) list?

echo "- Renaming file..."

for file in `find fldr -type f`
do
  newf=$(echo $file | rev | cut -c -6 | rev)
   mv -f $file fldr/$newpt
  echo "  * $file > $newf"
done

actual output...

- Renaming file...
  * file1a.txt > 1a.txt
  * file2a.txt > 2a.txt
  * file3a.txt > 3a.txt
  * ...

desired output...

- Renaming file...
  * file3a.txt > 3a.txt

I would like to see the one line always changing to show the current file only.

[BONUS] How would I get it to also display the n'th file it is renaming?

- 3 files renamed...
  * file3a.txt > 3a.txt

Where n is a cumulative sum/count of the files renamed.

SaultDon

Posted 2011-06-07T06:00:23.257

Reputation: 222

Answers

2

Just change the echo line to this:

echo -ne "\r  * $file > $newf                         "

The spaces on the end clear old output from the line.

Keith

Posted 2011-06-07T06:00:23.257

Reputation: 7 263

1Umm, I think it should be echo -ne "\r * $file > $newf Otherwise echo will not interpret escape characters. – darkdragn – 2011-06-07T11:37:32.230

1printf is more portable when it comes to escape chars: printf "\r * %s > %-50s" "$file" "$newf" – glenn jackman – 2011-06-07T12:25:18.450

Worked for me. But sure, printf is probably better, but I just did a simple modification to the original here. – Keith – 2011-06-07T14:34:22.900

Thanks! Looks promising. I will get to try it out this afternoon but I can see the logic. Will mark as correct when I get it working. – SaultDon – 2011-06-07T18:20:27.560

@chris You're right, I tried it, and it wouldn't work without the -ne I am doing this is in Bash on Ubuntu 10.04 if that makes any difference... Thanks for the help all. – SaultDon – 2011-06-08T01:52:09.983