[H-GEN] Useful bash Variable Manipulations

Anthony Towns aj at humbug.org.au
Fri Aug 8 07:18:41 EDT 1997


-----BEGIN PGP SIGNED MESSAGE-----

Hello world,

Ever tried typing "mv *.asc *.txt" to rename all your .asc files to
.txt?

And have you noticed how it doesn't work? (Newbies -- this is your cue
to try it. Don't do it where there are important files though)

Even though it _does_ work under _DOS_?

Well, have I got a tip for _you_!


	``  for i in *.txt; do mv $i ${i%.asc}.txt; done  ''


(okay, so it's harder than "C:\> move *.asc *.txt". The Unix way of
expanding wild card before the program is called is better enough in
general to make up for it) 


Basically, if you want to trim stuff off the end of a variable, use

	${variable%pattern-to-trim}

and if you want to trim stuff off the beginning, use

	${variable#pattern-to-trim}

Replacing # with ## and % with %%, will change it's behaviour from
trimming the shortest possible string to trimming the longest possible
string.

Note that the right hand side is _not_ a regexp, but rather uses the
same syntax as filename wildcards.

You can also do search and replace, determine the length of your
variable, obtain substrings and fill in default values.

Very nifty.

Search for "Parameter Expansion" in the bash manpage.

Cheers,
aj

- --
Anthony Towns <aj at humbug.org.au> <http://student.uq.edu.au/~s343676/>
I don't speak for anyone save myself. PGP encrypted mail preferred.

``Like the ski resort of girls looking for husbands and husbands looking
  for girls, the situation is not as symmetrical as it might seem.''

-----BEGIN PGP SIGNATURE-----
Version: 2.6.3ia
Charset: ascii
Comment: Key available at http://student.uq.edu.au/~s343676/aj_key.asc

iQCVAwUBM+sAm+RRvX9xctrtAQEx4gP/QU/Xmy9pOKDMoNCXvV2hqEjpDqcvuB50
YF1SuQuCgS6Mar6DCzgTapF2e11tPq+U3QDBWhd5seQ2pcsVIIRdtDx7Qbad9PdE
HeCweCahtJvQ9N1xC8kMh1DxaGTcAIjmefdZQjRtsjHglAuiF6+NGdZY04tukq34
9Sjsi7Ay84k=
=DzID
-----END PGP SIGNATURE-----

----------------------- HUMBUG General List --------------------------------
echo "unsubscribe general" | mail majordomo at humbug.org.au # To Unsubscribe



More information about the General mailing list