Friday, May 3, 2024
3
rated 0 times [  3] [ 0]  / answers: 1 / hits: 338  / 2 Years ago, fri, january 28, 2022, 5:56:44

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


More From » command-line

 Answers
4

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

[#6423] Sunday, January 30, 2022, 2 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
ticeate

Total Points: 497
Total Questions: 128
Total Answers: 112

Location: Samoa
Member since Fri, Nov 27, 2020
4 Years ago
;