Friday, April 07, 2006

Replace every instance of the text "Foo" and "Bar" with "Fox"

$ sed 's/ Foo\| Bar/ Fox/ g' README

Replace every instance of the text "Foo" with "Bar" in README

$ sed 's/ Foo / Bar / g' README

Output all the text from file Foo.txt except between “Chapter 2” and "Chapter 5"

$ sed '/Chapter 3/,/ Chapter 4/ p' book-draft

Output all the text from file Foo.txt between “Chapter 2” and "Chapter 5"

$ sed -n '/Chapter 2/,/ Chapter 5/ p' Foo.txt

Output lines 80 to 88 of file README

$ sed '80,88! d' README

Output line 88 of file README

$ sed '88! d' README

Saturday, March 18, 2006

Inserting a line of text before a line containing a pattern







Appending a line of text after a line containing a pattern







Monday, March 13, 2006

Comparing two string

if [ $foo = "foo ]; then
...
fi

Sunday, February 12, 2006

${filename%.*} Extracting the filename by stripping off the file extension

$ FN="filename.jsp
$ echo ${FN%.*}
filename

${filename##*.} Extracting the file extension of filename

$ FN="FileName.jsp"
$ echo ${FN#*.}
jsp

${#string} Getting the length of a string

$ WORD=Supercalifragilisticexpialidocious
$ echo $WORD
Supercalifragilisticexpialidocious
$ echo ${#WORD}
34

${var=default} If var is not set, set it to default

$ echo $username
null
$ echo ${username=`whoami`}
islandjoe
$ echo $username
islandjoe

${var-default} If var is not set, use a default

$ echo $username
null
$ echo ${username-`whoami`}
islandjoe
echo $username
null

Saturday, February 04, 2006

If arg is empty print the current working directory instead

Our Nautilus script named "Xyz":



Demo


If we select a file:



It returns the name of the file:



And if we don't select a file:



It returns the name of its current working directory:

How to get the parent directory of a folder

$ dirname `pwd`

In shell script:

VAR=${dirname `pwd`}

Friday, February 03, 2006

Special characters and operators

$var -Variable



${var} -Same as $var



${var-default} -If $var is not set, use the string "Morjens"



${var=default} -If $var is not set, set it to default and use that value.





${var+instead} - If $var is set, use instead. Otherwise empty string.




${var?message} -If $var is not set, print message. If $var is set, use its value.


Friday, July 29, 2005

Print only line 58 of a text file:

$ sed -n '58p' file.txt



The '-n' option suppresses printing of all lines