Friday, 1 March 2019

Bash string and path manipulation

Just some notes on bash variable manipulation.

Sub stringing

name="James"
echo $name ${name} # Same result
James James
echo ${name:0:2} ${name::2} # Print first 2 characters, can omit the zero
Ja Ja
echo ${name::-2} # Remove n characters from the end
Jam
echo ${name:(-2):1} # Start 2 characters from the end and print 1 character
e
len=2
echo ${name:0:len} # Prints first 2 characters (note use of len not $len)
Ja
echo ${cake:-death} # Outputs $cake or the text death
death
cake="cakes"
echo ${cake:-death}
cakes
Moving on slightly to path maniplulation.

fName=/path/to/my/file.name
echo ${fName%.name} # Removes suffix .name
/path/to/my/file
echo ${fName#/path} # Removes prefix /path
/to/my/file.name
echo ${fName%.name}.type # Removes .name and replaces with .type
/path/to/my/file.type
echo ${fName##*.} # Prints the files extension
name
echo ${fName##*/} # Prints filename and extension, equivilent to basename
file.name
echo ${fName#*/} # Removes initial /
path/to/my/file.name
echo ${fName##*/} # Filename and extension
file.name
echo ${fName/a/A} # Replace first occurance of a with A
/pAth/to/my/file.name
echo ${fName//a/A} # Replace all occurances of a with A
/pAth/to/my/file.nAme
echo ${fName/%name/NAME} # Replace suffix
/path/to/my/file.NAME
echo ${#fName} # Print the length
21
a1=test
a3=${a2-$a1} # a3 = $a2 or $a1 if $a2 not set
a4=${a2-"this is a test"} # a3 = $a2 or "this is a test" if $a2 not set

echo "a1=$a1 : a2=$a2 : a3=$a3 : a4=$a4"
a1=test : a2= : a3=test : a4=this is a test
echo ${a5:=$a1} # Set a5 to $a1 if not set
test
echo ${a1:+$a4} # Prints $a4 id $a1 is set
this is a test
echo ${a2:?value is not set} # Prints error message is a2 not set
bash: a2: value is not set
: '
This is how
you print a
multi line
comment
'

No comments:

Post a comment

Oracle CPU downloader

Every quarter I have to go through and download numerous patches for the Oracle CPU (Critical Patch Update). You have to view the CPU docume...