[clug] Bashism desired
steve jenkin
sjenkin at canb.auug.org.au
Tue Mar 12 00:37:17 MDT 2013
Scott Ferguson wrote on 12/03/13 12:47 PM:
> I often wish there was way to reduce repetition within a single command
> run in Bash to save typing and reduce errors.
> Perhaps there is and it's so obvious I've forgotten/keep overlooking it :/
>
> Examples:-
> 1. cp some_directory_path/some_file some_directory/some_file.variation
> 2. mv some_directory_path/some_file some_directory/some_otherfile
>
> Desired solution:-
> 1. cp some_directory_path/some_file $trick/some_file.variation
> or
> 1. cp some_directory_path/some_file $trick/.variation
>
> 2. mv some_directory_path/some_file $trick/some_otherfile
>
>
> Anyone know a Bash shortcut for this?
> aliases are OK (if no other way)
>
> TIA
>
> Kind regards
>
I use the ksh/bash regex/match functions a lot for renames and moves:
${var%regex-suffix}
${var#regex-prefix}
I tend to use the %% and ## variants, 'Longest match'
Example:
# check to see if I get my strings or regex's right...
#
for f in prefix*.pdf
do echo ${f#prefix} ${f%.pdf}
done|head ## note the use of 'head'. sometimes 'less' is better
## then edit the 'echo' into a mv, knowing its safe
#
for f in prefix*.pdf
do echo $f; mv $f "newdir/newprefix_${f#prefix}_${f%.pdf}.pdf"
done ## Note removal of 'less' or 'head' YMMV
# For more complex problems, I use a 'find' or 'ls -1' into xargs and
call a function or purpose written script (with same test using 'echo')
# this example not tested.
function do_thingy()
{
for f in "$@"
do
echo "$f"
done
}
find . -type f|grep '\.pdf$'|xargs do_thingy
## Or if I'm really slack... create a script with manual editing...
# replace command with your favourite editor
# I don't do 'echo', but rely on 'mv -i'
# doesn't mean I don't stuff up and have to then change the script to
fix it!
ls -1 >x.sh # grab a list of the filenames.
# Could use ls -1|grep ' ' > x.sh # to find files with spaces.
vi x.sh
:%s,.*,mv -i '&'^I'&', # create proforma 'mv' command.
# Don't type ^I, use <tab> key
# sometimes I use " not ' for quoting...
:%s,^I'prefix,^I'otherprefix'
:%s,suffix'$,new-suffix',
:wq
sh ./x.sh
# rm x.sh # when you're done...
## a lot to times, I just search for /^I'.*string*
## and change the thing by hand (removing spaces)
HTH
steve
--
Steve Jenkin, Info Tech, Systems and Design Specialist.
0412 786 915 (+61 412 786 915)
PO Box 48, Kippax ACT 2615, AUSTRALIA
sjenkin at canb.auug.org.au http://members.tip.net.au/~sjenkin
More information about the linux
mailing list