linux - `for f in *; do cp "$f" "$f"_copy; done` doesn't work because "foo.png_copy". How to fix it? -
on linux, command:
for f in *; cp "$f" "$f"_copy; done
doesn't work expected because "_copy" string appended after file extension, becoming foo.png_copy
instead of foo_copy.png
. how fix it? can slice string?
for f in *; prefix="${f%.*}" suffix="${f:${#prefix}}" cp "$f" "${prefix}_copy${suffix}" done
this finds filename's prefix trimming suffix matching ".*". note if filename doesn't have extension, entire filename; if has more 1 period, it'll remove last 1 (e.g. file named "this.that.etc.png", it'll trimmed "this.that.etc"). finds suffix slicing filename based on length of prefix (${#prefix}
); works expected whether or not removed.
warning: treat filename period in has having extension. example, "file_v1.0" copied "file_v1_copy.0".
note: if wanted, skip defining $suffix, , use ${f:${#prefix}}
inline in copy command, think clearer.
Comments
Post a Comment