I want to read two strings as parameters to bash script, these strings are meant to be extensions, then I want to replace the extension of files with the first extension to the second extension.
The best I could think about/find so far is:
#!/bin/bash
first=1ドル
second=2ドル
for files in *.1ドル
do
mv "$files" "${files%.1ドル}.2ドル"
done
Now, lets assume 1ドル is cpp, and 2ドル is C
My "doubts" are:
- would
.1ドルbe equal to.cpp? - Is
*.1ドルequal to say:*.cpp? - Is line 6 equal to
mv "$files" "${files%.cpp}.C"? - Would the previous code handle file names with spaces (like:
my file.cpp), or dots (likemy.file.cpp)?
I know I could've said the first 3 question in one question, but I need to understand what is exactly happening, and how will each operator (./*/%) deal with a given string in a parameter.
2 Answers 2
You have two typo's writing & instead of $ for addressing variables, but otherwise it should work.
Also, filenames with spaces will work, since you quoted them correctly.
Minor detail: I'd recommend renaming the variable $files to $file, since it always contains only a single filename from the list that is looped over.
-
1I would also add
--tomv(as inmv -- "$file" ...) to ensure it can handle file names starting with a-.Joseph R.– Joseph R.2014年01月21日 12:26:06 +00:00Commented Jan 21, 2014 at 12:26 -
@ Joseph R Good point, is there any other options that you recommend to add to 'mv'? or that the way it is written can already handle all kinds of of file names?user2750466– user27504662014年01月21日 13:41:43 +00:00Commented Jan 21, 2014 at 13:41
-
@user2750466 I'm no expert myself but I think this should cover most edge cases.Joseph R.– Joseph R.2014年01月21日 14:34:29 +00:00Commented Jan 21, 2014 at 14:34
Your code is correct with the minor note by Joseph R. about files containing a dash. However lines 2 and 3 seem redundant, because you don't use the variables first and second in the snippet.
To alleviate your "doubts" (assuming 1ドル is cpp, and 2ドル is C):
- The
.is not an operator here, so bash does just a parameter expansion on the1ドル. So the answer is yes,.1ドルis equal to.cpp - Parameter expansion has precedence over pathname expansion (link), meaning
*.1ドルis equal to*.cpp - Again, the line does what you suppose it does, because first the
1ドルis expanded to be handed to the pattern matching algorithm evoked by the% - The double quotes prevent bash from doing field splitting, which is what usually causes problems with filenames containing spaces
-
I have a quite stupid question: would the program work correctly also if 1ドル and 2ドル were replaced by first and second, I mean if I did for example: .first or *.first, that would give a similar result, right?user2750466– user27504662014年01月21日 15:30:26 +00:00Commented Jan 21, 2014 at 15:30
-
If you use
$firstand$secondthen yes. The reason is that the variable assignments from1ドルand2ドルno word splitting is performed either.Jaap Eldering– Jaap Eldering2014年01月21日 18:23:53 +00:00Commented Jan 21, 2014 at 18:23