0

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

2

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
  • 1
    Why not .bash? I name all my bash scripts this way, I think it’s a good practice to have the interpreter as the script file extension, this way you see what’s a sh script and what’s a bash one without opening the file. – dessert Jan 3 at 19:56
  • @dessert Because .sh scripts are typical for Bourne-shell scripts in general and extensions are generally a preference of the user/author :) There exit several /bin/sh or /bin/bash scripts on Ubuntu which don't use any extension at all either. A good example of that is on_ac_power – Sergiy Kolodyazhnyy Jan 3 at 20:06
  • Also generally a user shouldn't need to know if it's a bash script or not. As author you already know, so there's no point. – Sergiy Kolodyazhnyy Jan 3 at 20:12
  • 1
    @dessert Good point! A quick Google found points for .bash and for .sh (by convention). I guess ultimately it's personal preference. Personally I don't use it cause Gedit doesn't automatically syntax-highlight a .bash file unless it has a shebang. I might have also been thinking of the Python extension debate, where .py3 files won't even be recognized as modules. – wjandrea Jan 3 at 20:34
2

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.