2

I am trying to write a very simple bash script in order to add a file extension (.java) to a bunch of files that have no extension.

If they had an extensions (say .txt) I'd do this:

#!/bin/bash
for file in `*.txt`; 
do mv $file $file.java; 
done

My files, however, don't have an extension. How do I make the loop? I tried *. with no luck.

Thank you.

1

4 Answers 4

4
#!/bin/bash
for file in *; do
  mv "$file" "$file".java; 
done

If you only want to move files that do not already have an extension, try:

#!/bin/sh
for file in *; do
  test "${file%.*}" = "$file" && mv "$file" "$file".java;
done

Note that all of the double-quotes above are superfluous if your filenames are reasonable.

Sign up to request clarification or add additional context in comments.

4 Comments

That renames all files including those that do already have an extension.
Thank you, that did the trick :) I hope my question wasnt asked twice.
@Vicky Indeed it does, which is what the OP asked for.
For bash 3 and higher you can do write it simplier with mv ${file}{,.java}
0
ls -1 | nawk '/.txt/{old=$0;gsub(/.txt/,".txt.java",$0);system("mv \""old"\" "$0)}'

updated the answer from here

Comments

0
#!/bin/bash
for file in *.txt ; do mv $file `echo $file | sed 's/\(.*\.\)txt/\1java/'` ; done

1 Comment

Same as rename 's/.txt$/.java/' *.txt
0

Try:

find . -maxdepth 1 -type f | sed 's/^\.\///; /\./d' | while read x; do mv "$x" "$x.java"; done

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.