View on GitHub

NEH Institute materials

July 2017

Home | Admin | Week 1 | Week 2 | Week 3 | Misc

Programs and files 2

Repeating things and variables

Declare a variable with just its name, but refer to it with a leading $. For example:

for file in *.txt; do wc -l $file; done

The preceding declares a variable called file, which will be equal to all files in the current directory that end in .txt and then reports the number of lines in each.

In the first example below, % removes a matching string at the end of the filename (in this case, .txt), and we then append something else (in this case, .bak). This changes the extension on all .txt files to .bak; for example, it changes obdurodon.txt to obdurodon.bak. The second example keeps the .txt and appends .bak after it, changing obdurodon.txt to obdurodon.txt.bak.

Both commands as written, with cp, make copies, but if you replace cp with mv, they rename files.

for file in *.txt; do cp ${file%txt}bak; done 
for file in *.txt; do cp $file $file.bak; done

The environment

More about $PATH

Finding commands and files

System locale ($LOCALE and $LC_*)

Declare a variable with just it’s name, but refer to it with a leading $. Example:

 for file in *.txt; do wc -l $file; done

The preceding declares a variable called file, which will be equal to all files in the current directory that end in .txt, and then reports the number of lines in each.

Misc