1

I am trying to loop through all files located in a directory ending in .txt and rename them (replacing beginning with end). However I would like to take the output from this for loop and pipe it to a bash file so that I can check the file and make sure what I have written does what I want it to, then I can just execute the .bash file if what I see fits the task. I've tried

for file in *.txt ; do mv $file ${file//beginning/end} ; done | rename.bash

however this renamed the file and created an empty rename.bash

magladde
  • 113

2 Answers2

3

Put echo before mv. This will print the command instead of executing it.

As well:

  • Quote variables to avoid word splitting on spaces in the filenames. In this case you'll need to put quotes in quotes since you're outputting to a script.

  • I've never seen a .bash extension in use, so I'd prefer .sh instead for the output script.

  • You can't pipe directly to a file. Use output redirection > instead. If you need to use a pipe, use tee.

In sum:

for file in *.txt; do
    echo "mv '$file' '${file//beginning/end}'"
done > rename.sh
wjandrea
  • 14,504
3

Because mv doesn't output anything, and you can't pipe into a file.

What you can do is create a bash script using redirector:

for file in *.txt
 do
 echo "mv $file $(some command to manipulate the text)" >> script.bash
done

This will append the command to the file.

vidarlo
  • 23,497