Thursday, October 30, 2008

Best Free PDF Tools

A PDF tool comes in handy when you need to do PDF documents for any of the following:
  • Merge, split or reorder pages of a PDF file, rotate or crop PDF pages;
  • Add a header, footer or watermark;
  • Encrypt or decrypt PDF documents;
  • Make annotations in PDF pages;
  • Change PDF document properties;
  • Convert PDF to text or images, or vice versa;
  • Other functions.
Top PickPDFill PDF ToolsPDFill PDF Tools is my favorite for its clean and nice user interface with most of the functions covered, such as merge, split, reorder or rotate pages, add headers and footers complete with page numbers, etc.
Watermark can be added by typing in any text such as ‘DRAFT’ for documents to be reviewed, or can be added by a background image in PDF format.
Some additional features are supported such as encrypt and decrypt with security options, reformat multiple pages into one page, PDF form field operations, convert PDF to images or vice versa, and convert PostScript file to PDF.
However, converting PDF to text, making annotations or changing document properties, such as title and author, are not supported in this free software. Instead, they are available to some other programs listed in the lower section.
PDFTK BuilderPDFTK Builder may be used as an alternative. It can merge or reorder selected pages of PDF files at one go. This is a better idea to have merging and reordering of pages done at the same time.
It also supports split, rotate, background/stamp and encrypt features. Besides these, it has no other additional features.
It also lacks a basic function, as available to PDFill PDF Tools, for adding a background text as a watermark to PDF documents. This function is much needed when we need to mark a PDF document as 'Confidential', 'Draft' or in any other text in the background of the pages.
jPDF TweakIf you just need more features, jPDF Tweak will be a good choice but its user interface will not be better than any of the above two applications.
Its merge, split and reorder functions are available under ‘input’ tab with a new filename to be entered under ‘output’ tab.
jPDF Tweak offers rotate, crop, watermark and format multiple pages, change page numbers and chapter bookmarks, and encrypt functions.
It allows adding attachments to PDF documents, setting viewer preference and document properties including title, author, subject and keywords.


Besides the above applications, there are other free programs supporting part of the functions. They are listed below for quick reference.
To only merge and split PDF, you may also look for Gios PDF Splitter And Merger. It allows drag and drop to add documents.
Some PDF to Word ConverterTo convert PDF to text, my choice is Some PDF to Word Converter, which allows removing line breaks and preserves paragraphs with soft returns. It also keeps images but does not preserve hyperlinks for the version under review.
Online conversion from PDF to text through emails is also available free with kool Converter, which preserves paragraphs and hyperlinks in converted PDF files.
Sun PDF Import Extension to OpenOffice.org allows PDF documents imported in Draw and Impress to preserve layout and edit small portion of text. PDF import in Writer is to be developed.
FreeOCR.netFreeOCR.net, which is a scan and OCR (Optical Character Recognition) program, is a good choice to extract text from scanned PDF documents.
To convert text to PDF, OpenOffice.org Writer is a good freeware to export text to PDF. By doing so, hyperlinks or bookmarks are preserved in exported PDF files. To get almost the same good result, kool Converter or Document Converter eXPress offers online conversion to PDF as well.
Alternatively you may install a virtual PDF printer, such as Bullzip, to create a PDF file by printing text or other contents via the PDF printer. By doing so, hyperlinks and bookmarks are usually not preserved in the resulted PDF file. Refer to the category of Best Free PDF Writer for selecting a PDF printer.
PDF-XChange ViewerTo annotate PDF documents, most of the tools do not support it, but PDF-XChange Viewer, covered under the category of Best Free Non-Adobe PDF Reader, does it.
PDF-XChange Viewer also allows highlighting, crossing or underlining selected text, and filling up PDF forms with a built-in typewriter. It is surprisingly more than a viewer!
To make fillable PDF forms, PDFescape is available free via online editing. Other features such as whiteout, insert text or basic symbols are included.
To add attachments to PDF, try PDF Bundle.
To add page numbers, SpeedPDF Page Numberer allows variable formats of page numbers, whereas A-PDF Number has fewer options.
To add watermark, PDF Watermark Creater adds a text as watermark, and SpeedPDF Stamp adds an image as watermark.
To set viewer preference and metadata, BeCyPDFMetaEdit is a good find. It allows editing metadata about author, title, subject, keywords, producer and creator, customizing viewer preferences, bookmarks, page labels, page transitions for slide shows and encryption of PDF documents. TweakPDF is another alternative with fewer options.
To compress a PDF file, try Free PDF Compressor. It allows decompression of a PDF file as well.
To convert PDF versions, use PDF Version Converter for conversion of a PDF file between different versions for compatibility purpose.


Author: PlotSoft
Version: 6.0
Date: 10 October 2008
Download File Size: 7 MB
License: free
Operating Systems Supported: Windows 98 to Vista
64 Bit version available: yes
Portable version available: no
Other languages supported: no
Additional Software Required: Free GhostScript
Author: Augus Johnson
Version: 3.5.3
Date: 7 June 2008
Download File Size: 2 MB
License: GNU General Public License
Operating Systems Supported: Windows Version of PDFTK
64 Bit Capable: no
Portable version available: yes
Other languages supported: no
Additional Software Required: no
Author: Schierlm
Version: 0.9
Date: 10 September 2007
Download File Size: 724 KB
License: free
Operating Systems Supported: Windows 95 to XP
64 Bit Capable: no
Portable version available: no
Other languages supported: no
Additional Software Required: Java 5 or higher
Author: SomePDF
Version: 1.5
Date: n/a
Download File Size: 784 KB
License: free
Operating Systems Supported: Windows 2000 to Vista
64 Bit Capable: no
Portable version available: no
Other languages supported: no
Additional Software Required: no
Author: Softi
Version: 2.5
Date: 23 October 2008
Download File Size: 5 MB
License: free
Operating Systems Supported: Windows 2000 to Vista
64 Bit Capable: no
Portable version available: no
Other languages supported: yes
Additional Software Required: no

Monday, October 27, 2008

电子工程技术人员必须知道的网络资源大全

http://www.emcchina.org/ 电磁兼容
http://www.pcbtech.net/firstservlet PCB技术网
http://www.21ic.com/ 相信大多数人也都知道这里吧!
http://www.c51bbs.com/c51blog/index.html C语言编程
http://www.datasheet.com.cn/ 查询资料很不错,国内网站但资料是英文的
http://www.cndzz.com/down/ 电子资料下载
http://www.chinadz.com/icver/ 电子资源网
http://www.upsdn.net 便携系统开发
http://www.alldatasheet.com 不错的器件资料网站,内容很全,相当不错,英文
http://www.ednchina.com/ 电子设计技术
http://www.mculib.com/ 三毛电子世界

Friday, October 24, 2008

PDF转换word格式的方法总结

全面接触PDF:最好用的PDF软件汇总》中主要介绍了pdf生成工具,但经常有网友寻找PDF2doc(pdf转word)软件,总结如下。

说明:

- pdf 无法编辑,这不是缺点,而是它的定位。
- pdf 虽然无法编辑,但可以进行注释。
- 为什么要转换为非pdf格式?技术上比较合理的原因是进行再编辑,但这样做的时候请注意版权。
- 是否一定要转word?如果文档只有文字,则不如转为txt或rtf。如果还有一些不算复杂的图表、图片,转为htm也是可以接受的。但如果格式复杂,或者你对 html 不了解,也不妨转为doc格式[1]
- 本文以及全部善用佳软的根本目标是原则和方法,而不是软件。如果念条咒语,或挥几下手就能把pdf转为word,为什么一定要软件呢?

方法1:通过Gmail邮箱转换

恭喜Gmail用户。把pdf发到Gmail信箱,在附件一侧,就有”以HTML格式查看”链接。如果你一定需要doc格式,复制html的内容吧。
pdf2doc-gmail
优点:速度快、可信、很多人已经有Gmail信箱(没有?注册一个吧);各种语言编码的文字都应该可以转换
缺点:pdf中的图片好象有问题

方法2:pdfundo.net在线转换

在线的http://pdfundo.net(名称很有意思),可以上传pdf文档,30秒-几分钟即可转换为doc,并给出下载链接。它也有相应的客户端软件。[via lifehacker]
pdf2word

优点:免费、在线、直接生成doc
缺点:试转了一份台湾朋友制作的pdf(原始文件也根本不是word,繁体中文),发现很多汉字无法显示。

方法3:共享软件 e-PDF To Word Converter

善用佳软很少有pdf2doc需求,并没用过e-PDF To Word Converter。小众软件《e-PDF - PDF 转换 Word 文档》称 “e-PDF 可以把 PDF 文件比较完美的转换成 Word 文档,我用104页的 PDF 做了测试,除了少数地方,其余都属于完美转换了。”

网上其他介绍:
e-PDF To Word Converter 是一款将AdobePDF文档转换成 Word 文档的工具软件,它支持文字,图像及其它内容的输出。这款软件可以脱离 Microsoft Word,Adobe Acrobat 或 Acrobat Reader 独立运行。完美的中文支持和原始版面转换,基本做到了百分百的原汁原味……
目前唯一发现的不足,数字会被转换成全角数字,不知道可否在word中批量把数字换回半角,另外有些文字大小会小一号。试用了超多的PDF转Word工具了,应该说这个是所见过版面保留最好的了,虽然还是有点缺憾。

优点:见上
缺点:不免费,USD35
e-PDF To Word Converter

结论

偶尔有pdf2doc需求的网友,建议先试用在线的Gmail 和 PDFundo 。如果质量不能满足需求,或转换的数量、速度有更多要求,可以试用/注册 e-PDF To Word Converter。
但无论哪种办法,在行动之前都值得想一下:真有必要从pdf转为word吗?

Thursday, October 23, 2008

Ubuntu 8.04下安装Synopsys DC 2007

研究探索了好长一段时间,终于在Ubuntu 8.04下成功安装synopsys dc2007.03-SP5。

网上有许多教程但都不是很详细,因此发出来,高手就见飘过,仅供新手学习参考。

1)首先安装installer.

我选的installer是1.8版. 直接解压缩到你想安装的目录就可以.我是安装到/home/mars/EDA/Synopsys/installer

2)接下来安装scl

scl是synopsys的license管理器,这里我选择安装的是10.9.1d版本.这个版本也是直接解压缩到目标目录.

同样安装在/home/mars/EDA/Synopsys/scl.

我用的系统是Ubuntu 8.04,这里选择那个Linux的压缩包就可以.

3)然后安装DC2007.

将DC2007 的common和 linux平台文件解压缩到同一目录下.解压之后会有一个syn.taz文件

到installer目录里执行 ./installer -gui 启动installer的图形安装界面.(这里提一下:有可能因为权限问题执行不了,我把home/mars/EDA整个目录权限改了就好了)

按照提示选择 .taz文件即将目录指向那个syn.taz所在的目录,一路next,就可以安装上DC2007了.

4)DC2007的license以及设置

这一步很关键!参考了网上几篇DC的license设置和环境的设置,最后成功了!

首先是license. 这里我是用EFA-LicGen0.4b和sssverify来产生license的.

把license放到你想存放的目录. 我的是放在/home/mars/EDA/Synopsys/license目录里。

然后打开用户目录下的.bashrc文件设置环境变量,在末尾加上如下内容:

###############################################################################
alias lmli2='/home/mars/EDA/Synopsys/scl/linux/bin/lmgrd -c /home/mars/EDA/Synopsys/license/license.dat -l /home/mars/syn_lic.log'
export SYNOPSYS=/home/mars/EDA/Synopsys
export LM_LICENSE_FILE=27000@mars
export LM_LICENSE_FILE=$SYNOPSYS/license/license.dat
export PATH=$SYNOPSYS/bin:$PATH
alias dv=$SYNOPSYS/bin/design_vision
###############################################################################

其中的路径要根据你自己安装和设置的具体路径修改. .设置完后重启,在终端运行lmli2启动license, 在/home/mars/目录下的syn_lic.log文件会记录license启动的情况.

OK,马上运行dv& 看吧,此时应该能进入dc了.如果没问题,那么dc_shell-t 等能运行. 若还提示有问题,看错误提示进行修改.


Monday, October 20, 2008

Top 10 IKEA Furniture Mods

10. Make an Allen wrench drill bit.

Put together a four-leg desk by hand using one of the Allen wrenches IKEA throws in every box, and you'll have an idea what Repetitive Strain Injury feels like. If you've got one left from a previous project, IKEA or otherwise, consider snipping off the angled parts and sticking the long end into a drill. Now you could chain-assemble a dozen funny-named desks, drawers and other furniture with nary a complaint, at least until the battery wears out.

9. Make your workspace cordless.

IKEA doesn't have a cordless desk anywhere in their gigantic stores, but they do offer a $10 "Signum" under-desk attachment that makes elegantly cordless workspaces—like those detailed by Adam and Gina—darn simple. Gina mounted hers under her desk next to an extra-wide, spaced-out power strip hung with some twisted wire. Both guides explain their de-cording process in detail.

8. Embed a scraps bowl into your counter top.

Rachael Ray espouses the time-saving and clean-making convenience of the "garbage bowl," a container you shove all your scraps, rinds, small messes, and anything else destined for the trash or compost heap instead of running over to it. If you agree, or tend to make a lot of salads or mixed dishes, embedding a stainless steel bowl into your counter or a wheeled butcher cart might make a lot of sense. Easy to clean out, always available when needed, and it's one less dish you have to clean out after a serious meal. It takes a fair deal of tool work, including router work, but it's perfect for the butcher carts you occasionally see on sale at IKEA, Target, or any other big-box store.

7. Create seriously simple knife storage.

If you're not the type who likes to show off and explain their knife collection, a simple saw cut into any non-permanent rack can save you a good deal of counter or wall space. One hacker thought it worked well on a $60 Bekvam cart, but if you weren't afraid to take a circular (or band) saw to your counter space, and you don't have long-limbed kids to worry about, it makes for a nice quick-grab workspace in the kitchen.

6. Make a headphone stand from spare parts.

This one's more of an inspiration than a do-this-exactly project. IKEA Hacker picks up a photo-filled forum post detailing how a few spare parts from IKEA furniture—picked up for cheap at the store or yanked from furniture on its way to the curb—can be made into a great place to stash your noise-canceling headphones. The object-oriented parts from many IKEA kits can be put to similar problem-solving use, so it's often worth keeping them in storage until inspiration strikes.

5. Wall-mount a bike rack.

Need to stash two bikes with minimum floor space use? One clever craftsmen took $40 in parts from IKEA's spare catalog—helpfully linked in the IKEA Hacker post—and a few easily-obtained materials to create a solid, economical rack for his two bicycles. Not too hard, no welding required, and you can cut and shape it to fit your particular domicile.

4. Turn an IKEA door into a desk.

When it comes down to it, your desk need not be much more than a slab that holds your work things which you can stand to look at. Taking a cue from the college playbook, Jonas grabbed a door from the Pax closet system and made it into his workspace. The door itself wasn't all that wide, so he grabbed two Lack racks (those weird, weird names) and created a DIY desk he could be proud of. It's just a few screws and a bit of time between you and the same result, if you want it.

3. Put together a switchable charging station.

If you dig the idea of a box to contain all your power-hungry gadgets (as illustrated below), but not the energy leeching (or battery weakening) of having your gear plugged in constantly, Instructables takes IKEA box-modding to a higher level. It costs only a tiny bit more than the original, and leaves you with the dual good feelings of DIY accomplishment and eco-friendliness.

2. Make your own custom charging station.

Many of IKEA's smaller storage containers and desktop organizers can be converted into gadget/laptop charging stations that eliminate cord clutter and are often indistinguishable from the rest of your (potentially) orderly desk. You can, for example, turn a $15 Estetisk compartmentalized storage bin into a wooden, laptop-gripping charge station. If your gear goes somewhere other than your desk, a $3 plastic box conversion keeps your cables out of the way and your phones, MP3 players and other toys together.

1. The Helmer DIY server rack.

No, you probably won't need six quad-core processors and the associated fans, RAM sticks, and motherboards for any project you're working on (or even dreaming of). But freelance 3D animator Janne is an inspiring reminder that paying serious cash for the box your computer merely sits in isn't always necessary—especially when units like the $40 Helmer make for such nice CPU homes.

Tuesday, October 14, 2008

Top 10 Printable Paper Productivity Tools

10. Print out in-a-pinch graph paper or rulers.

ruled_paper.jpgSometimes it's just easier to write or sketch out your thoughts when there's guidelines on your paper, as you may remember from grade school. If your office or home office doesn't keep a stack of it handy, there are many DIY solutions. Printable Paper keeps a virtual Staples aisle of graph and lined paper on hand, while PrintFreeGraphPaper.com lets you click to determine your sheet's parameters. If you just need to know whether an object or life-sized picture is 4.5 inches but you're missing a ruler, try a collection of the paper version.


9. Turn PDFs into a palm-held booklet.

bcreator_cropped.jpgIf you've got reading to do on your commute, or anywhere you're on the go, it's a lot more convenient if it fits in your pocket. Spare yourself staple-torn sheets and awkward folding with BookletMaker, which takes in PDFs and reprints them as readable, multi-page booklet(s) you can order and customize. Note that PocketMod (you'll see it below) and Adobe itself have a similar capability baked-in, but without the multi-booklet convenience.


8. Print a custom CD case.

paper_cd_case.JPGAs replacements for busted jewel boxes or containers for thoughtful gift mixes, a paper CD case is an attractive, value-added way to keep scratches and thumbs off your loose tunes or programs. The link above shows how to fold and decorate your paper sheath; for a more straight-forward artist/album/track listing, check out paper CD case.


7. Fold a paper wallet.

paper_wallet.jpgWe're obviously big fans (in gawking at, if not always assembling) of DIY wallets of all types, but the durable paper wallet detailed at Instructables is truly cheap, conversation-starting, and, if made out of Tyvek film, durable and water-proof. It's also super-thin, which your well-worn back pockets will thank you for.


6. Fold a 3D, 12-sided desk calendar.

calendar-paper.pngAdmittedly, a dodecahedral, AD&D-style calendar isn't as useful as your standard at-a-glance models, but it sure outdoes your fellow cubicle workers for ingenuity. Generate your own print-and-fold PDF at Ole Arntzen's site, and check out illustrated assembly instructions at simplehuman.


5. Plan with a "Candy Bar" calendar.

compactcal_sm.jpg Add a timeline to your project notebook or wallet for a computer-free date reference with Dave Seah's Compact Calendar—an Excel worksheet you download and mark off important dates on (original post). The "candy bar of time" layout of continuous days makes highlighting blocks of dates easy. For those who want an at-a-glance calendar at their desk, a monitor strip calendar offers similar no-click convenience.


4. Template your note-taking.

cornell_method.jpgMany college graduates couldn't look back at their notes from any lecture and make much sense of them at this point—unless they took them right the first time. Whether you're in academia or just need better notes from your meetings, the Cornell Method of note-taking breaks down raw sentences into workable concepts and items. Once you've learned the basics, you can pre-print Cornell-formatted templates at Cornell-Notes to force your hand, and your brain, to do the right thing.


3. Print out a personal CEO with the Printable CEO.

printable_ceo.jpgWhen you don't have an actual CEO making sure you're working on the important things in the business of your life, you can print one out. The Printable CEO is a simple checklist that constantly asks "When is something worth doing?" Geared to those building sales-based services, you can easily re-purpose the Printable CEO for any goals or decisions, as Lifehacker alumnus Keith Robinson found out.


2. Print your own PocketMod mini-organizer.

PocketMod.gifPocketMod, a free webapp that creates slick-looking printouts you fold a few times into a mini-organizer, embraces the very reason paper is still around in this ultra-digital age—it's portable, it's cheap and recyclable, and you don't need special tricks to embed daily/weekly/monthly planners, a calendar, RSS feeds, notes, or anything else into it. The original design will keep you busy for some time, but you can also track your mileage and workout schedule, keep the kids (hopefully) entertained, and create walk-around maps. The PocketMod is a truly extendable system that anyone can use.


1. Configure your own planner with the D*I*Y Planner 3.0.

DIY_planner.jpgYou can drop some serious cash on expensive paper planners at the fancy stationary store, but they always have too many pages of this but never enough of that. Instead, configure and refill your planner with the wide range of printable D*I*Y Planner templates, a collection of more than 100 lists, calendars, task management, thought trees, and other helpers in all the standard paper sizes. They've also added a Hipster PDA edition (here's more on clever little hack), stylish covers, and much more.

Monday, October 13, 2008

15+ "must have" Cisco Cheat Sheets

Below is the link list to essential Cisco related cheat sheets (collection of notes or quick reference guides whatever). By the way, we don't recommend to cheat anything and/or do a cheating of any sort by means of using these materials ;)

1. Cisco IOS Versions (preview, what’s this?)
2. Physical Terminations/Connectors (preview, what’s this?)
3. VLANs (preview, what’s this?)
4. Quality of Service (preview, what’s this?)
mpls cheat sheet small 5. MPLS (preview, what’s this?)
6. IP Access Lists (preview, what’s this?)
7. Spanning Tree (preview, what’s this?)
8. OSPF (preview, what’s this?)
9. EIGRP (preview, what’s this?)
10. BGP (preview, what’s this?)

11. General Cisco IOS cheat sheet (router/switch commands etc.)
12. Cisco Commands for Beginners
13. Descriptive list of Cisco Commands (fresh)
14. Cisco IOS Firewall Cheat Sheet (Official Design Guide)
15. Cisco - Ethernet Encapsulation (in pdf)
16. Mini CCNA Cheat Sheet
17. CCNA Cheat Sheet (commands debugging)
18. Connector Pinouts Cheat Sheets

Great thanks to Jeremy Stretch (author of packetlife.net) for the first 10 cheat sheets from above list (to get them all just download this package).

Sunday, October 12, 2008

Ubuntu 8.04下安装Cisco VPN Client

下面简单说明下在Ubuntu 8.04下安装Cisco VPN Client的过程。

Cisco 的 VPN Client Linux 版总是更新得很慢很慢,而且出来的东西总要打补丁。一个那么大的公司,出个软件还要别人帮忙把补丁打上,而且版本更新的时候从来没想过把这个bug改掉。

进入这里(http://www.megaupload.com/cn/?d=NSUOI4X1)下载Cisco VPN Client,文件名是vpnclient-linux-x86_64-4.8.01.0640-k9.tar.gz。

进入这里(http://www.megaupload.com/cn/?d=YEXM6EUK)下载补丁文件vpnclient-linux-2.6.24.diff。

解压上面第一步下载的VPN Client:

$ tar xzf vpnclient-linux-x86_64-4.8.01.0640-k9.tar.gz

会解压出一个叫vpnclient的文件夹。把上面第二步下载的补丁文件vpnclient-linux-2.6.24.diff放到这个文件夹里。

在终端中进入文件夹vpnclient,输入以下命令打补丁:

$ patch <>

打完补丁后用下面的命令安装Cisco VPN Client:

$ sudo ./vpn_install

如果要你输入什么东西,回车用默认值就行。可能会有一堆警告消息,不用管它。

装完后把你的.pcf文件放到/etc/opt/cisco-vpnclient/Profiles/里。

用下面的命令启动VPN Client:

$ sudo /etc/init.d/vpnclient_init start

如果不打补丁,在这里会出现类似下面的错误,VPN不能正确启动。

Starting /opt/cisco-vpnclient/bin/vpnclient: insmod: error inserting ‘/lib/modules/2.6.20-15-386/CiscoVPN/cisco_ipsec.ko’: -1 Invalid module format
Failed (insmod)

VPN Client启动后用下面的命令连接VPN(这里假设你的.pcf文件名是 XXX.pcf),注意不要加文件的后缀名.pcf:

$ sudo vpnclient connect XXX

Sunday, October 5, 2008

Adding Cisco.com Searches and Tools to Your Browser

http://www.cisco.com/web/tsweb/searchplugins/plugin_homepage.html#

This page shows how easy it is to add Cisco.com tool and search plugins to your Internet Explorer 7 and Firefox 2/Firefox 3 browser.
Just click the links below for the Cisco tools and searches you want to add to your browser.

Tools

Searches



Managing plugins for Firefox 2 and Firefox 3 browsers.


  1. Open the search pulldown window and select "Manage Search Engines".

    pulldown

  2. This panel allows you to reorder search plugins or delete them.

    manage



Managing plugins for Internet Explorer 7 browser.


  1. Open the search pulldown window and select "Change Search Defaults".

    manage

  2. This panel allows you to remove search plugins from your browser. Note that Internet Explorer 7 doesn't give you any options for setting the order of the search plugins.

    manage - step 2


The Plugin Available Indicator


When browsing www.cisco.com you may notice the search plugin pulldown change color. This indicates that a browser plugin is available.

Firefox 2/Firefox 3
Internet Explorer 7
ff indicator
ie7 indicator


Open the pulldown box and select the plugin to add.



ff step1
ie7 step 1

Submit feedback about Cisco Search Plugins here.

Thursday, October 2, 2008

Bash Parameter Expansion

If you use bash you already know what Parameter Expansion is, although you may have used it without knowing its name. Anytime you use a dollar sign followed by a variable name you're doing what bash calls Parameter expansion, eg echo $a or a=$b. But parameter expansion has numerous other forms which allow you to expand a parameter and modify the value or substitute other values in the expansion process.

Parameter expansion comes in many forms in bash, the simplest is just a dollar sign followed by a name, eg $a. This form merely substitutes the value of the variable in place of the parameter expansion expression. The variable name can also optionally be surround by braces, eg ${a}. If the variable name is immediately followed by characters that could be part of a variable name then the braces are needed to delimit the variable name, for example if you remove the braces from echo ${a}bc bash will try to expand the variable "abc" rather than "a".

One useful form of parameter expansion is to use a default value for a variable if it is not set. This is done with the syntax: ${VAR:-DFLT}. You might use this to allow your code to be modified via variables from the environment. Consider the following from a script, call it test.sh:

  TEST_MODE=${TEST_MODE:-0}
...
if [[ $TEST_MODE -eq 0 ]]; then
echo "Running in live mode"
else
echo "Running in test mode"
fi
Normally the script runs in "live" mode but if you run it via:
  $ env TEST_MODE=1 sh test.sh
it runs in test mode.

You might also use the default value expansion with command line arguments or values from a config file, for example:

  # set cmd_param_x to 1 if seen on the command line
...
if [[ ${cmd_param_x:-0} -eq 0 ]]; then
echo "-x not specified"
else
echo "-x specified"
fi

Another useful form of parameter expansion is to expand a variable and do string substitution on the value using the form ${VAR/search/replace}. For example:

  VAR=aabbcc
echo ${VAR/b/-dd-}
outputs "aa-dd-bcc". Note that only the first instance of the search string is replaced, if you want to replace all instances use a double slash:
  VAR=aabbcc
echo ${VAR//b/-dd-}
which now outputs "aa-dd--dd-cc".

There are also expansions for removing prefixes and suffixes. The form ${VAR#pattern} removes any prefix from the expanded value that matches the pattern. The removed prefix is the shortest matching prefix, if you use double pound-signs/hash-marks the longest matching prefix is removed. Similarily, the form ${VAR%pattern} removes a matching suffix (single percent for the shortest suffix, double for the longest). For example:

  file=data.txt
echo ${file%.*}
echo ${file#*.}
outputs the file base and extension respectively ("data" and "txt").

Note: if you have trouble remembering which is which of these two syntaxes, the "#" is to the left of the "%" key on your keyboard, just as prefixes come before suffixes. Also note that these are glob patterns not regular expressions.

Another expansion that exists is to extract substrings from the expanded value using the form ${VAR:offset:length}. This works in the expected form: offsets start at zero, if you don't specify a length it goes to the end of the string. For example:

  str=abcdefgh
echo ${str:0:1}
echo ${str:1}
outputs "a" and "bcdefgh".

This form also accepts negative offsets which count backwards from the end of the string. So this:

  str=abcdefgh
echo ${str:-3:2}
produces "abcdefgh"... oops, what happened there? What happened was that bash misinterpretted what we wanted because the expansion looks like a default value expansion: ${VAR:-DFLT}. First time I tried this I stared at it for quite a while before a light came on as to how to do it (without using a variable [see below]):
  str=abcdefgh
echo ${str:$((-3)):2}
which outputs the desired value "fg". The "$((...))" causes bash to treat the value as an arithmetic expansion (ie a number). Another slightly longer way of doing this is:
  str=abcdefgh
i=-3
echo ${str:$i:2}

The final form of parameter expansion I want to mention is one which simply expands to the length of the variable's value, its form is ${#VAR}. So for example:

  str=abcdef
echo ${#str}
outputs "6".

Using these forms of parameter expansion in your shell scripts can simplify and shorten your scripts. These are not the only forms of parameter expansion that bash supports but they're the ones that I've found most useful over time. For more information see the "Parameter Expansion" section of the bash man page.

p.s. Note that all of the above forms of parameter expansion also work with bash's Special parameters: "$$", "$0", "$1", etc.