Archive for the ‘bash’ Category

Iterating over a list of tuples in bash

Posted 21 Jul 2010 — by maxhaussler
Category bash, linux

I’ve shown previously how to rename many files on the command line. That solution required a 2nd textfile in the format oldname<space>newname<return>.

Sometimes it is easier if there is no external file and we simply want to iterate over a list that is part of the script. The command to use in this case is called set, which will split on the character in the variable IFS (=internal field separator?).


for i in a,b c,d ; do IFS=","; set $i; echo $1 $2; done

Will output:

a b
c d

Translate filenames

Posted 19 Apr 2010 — by maxhaussler
Category bash, linux

Sometimes you have to apply a set of Unix-commands based on data from a textfile. A very common example is a list a files and in addition a table (textfile) with lines containing the data on how to renames filenames to new filenames, like (oldFilename,newFilename). I always forgot how to code this, so here is an example shell script that accepts one parameter (the textfile) and renames files accordingly in the current directory:

cat $FILE | while read old new
    mv $old $new

Add headers to a file (add line to the beginning of a file)

Posted 25 Nov 2009 — by pedro
Category bash, linux

Let’s suppose you want to add your favourite line (STRING) to the first line of an existing file, which includes escaped characters such as \t or \s.

Entered your STRING with the following syntax and pass it the line editor Ex:

Here an example
$ echo -e “1i\nthis is my favourite line which can handle\ttabs\n.\nwq” | ex -s myfile

This command will add the text “this is my favourite line which can handle tabs”