1. Home
  2. Computing & Technology
  3. Linux

Bash Guide For Beginners

From

9.1.2. Examples

9.1.2.1. Using command substitution for specifying LIST items

The first is a command line example, demonstrating the use of a for loop that makes a backup copy of each .xml file. After issuing the command, it is safe to start working on your sources:


   

[carol@octarine ~/articles] ls *.xml
file1.xml file2.xml file3.xml

[carol@octarine ~/articles] ls *.xml > list

[carol@octarine ~/articles] for i in 'cat list'; do cp "$i" "$i".bak ; done

[carol@octarine ~/articles] ls *.xml*
file1.xml file1.xml.bak file2.xml file2.xml.bak file3.xml file3.xml.bak

This one lists the files in /sbin that are just plain text files, and possibly scripts:


   

for i in 'ls /sbin'; do file /sbin/$i | grep ASCII; done

9.1.2.2. Using the content of a variable to specify LIST items

The following is a specific application script for converting HTML files, compliant with a certain scheme, to PHP files. The conversion is done by taking out the first 25 and the last 21 lines, replacing these with two PHP tags that provide header and footer lines:


   

[carol@octarine ~/html] cat html2php.sh
#!/bin/bash
# specific conversion script for my html files to php
LIST="$(ls *.html)"
for i in "$LIST"; do
NEWNAME=$(ls "$i" | sed -e 's/html/php/')
cat beginfile > "$NEWNAME"
cat "$i" | sed -e '1,25d' | tac | sed -e '1,21d'| tac >> "$NEWNAME"
cat endfile >> "$NEWNAME"
done

Since we don't do a line count here, there is no way of knowing the line number from which to start deleting lines until reaching the end. The problem is solved using tac , which reverses the lines in a file.


   Prev    Home    Next
   Repetitive tasks    Up    The while loop

* License

* Bash Guide For Beginners Index

Explore Linux
About.com Special Features

The Best Web Trends of the Decade

A look back at the best innovations, ideas and technologies over the last 10 years, More >

Family Tech Center

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

  1. Home
  2. Computing & Technology
  3. Linux
  4. Linux Documentation
  5. Bash Guide for Beginners
  6. Bash Guide For Beginners - 9.1.2. Examples

©2009 About.com, a part of The New York Times Company.

All rights reserved.