linux poison RSS
linux poison Email

Bash Script: String manipulation (Find & Cut)

${parameter#word}
${parameter##word}

Remove matching prefix pattern. If the pattern matches the beginning of the value of parameter, then  the  result  of  the  expansion  is the expanded  value  of  parameter  with  the shortest matching pattern (the ``#'' case) or the longest matching pattern (the ``##'' case) deleted. 

${parameter%word}
${parameter%%word}

Remove matching suffix pattern.  If the pattern matches a trailing portion of the expanded value of parameter, then the result of the expansion is the expanded value of parameter with the shortest matching pattern (the ``%'' case) or the longest matching pattern (the ``%%'' case) deleted. 

Below bash script explains the concepts of find and cut the string within the string, feel free to copy and use this script.

Source: cat string_cut.sh
#!/bin/bash

var="Linuxpoison.Linuxpoison.Linuxpoison"
echo
echo -e "Value of var is: $var"
echo "--------------------------------------------"
echo 'Find all *nux from the start of the string and cut ${var##*nux} :'
echo ${var##*nux}

echo "-------------------------------------------"
echo 'Find the first *nux from the start of the string and cut ${var#*nux} :'
echo ${var#*nux}

echo "-------------------------------------------"
echo 'Find all .* from the back of the string and cut ${var%%.*} :'
echo ${var%%.*}

echo "------------------------------------------"
echo 'Find first .* from the back of the string and cut ${var%.*} :'
echo ${var%.*}

Output: ./string_cut.sh

Value of var is: Linuxpoison.Linuxpoison.Linuxpoison
--------------------------------------------
Find all *nux from the start of the string and cut ${var##*nux} :
poison
-------------------------------------------
Find the first *nux from the start of the string and cut ${var#*nux} :
poison.Linuxpoison.Linuxpoison
-------------------------------------------
Find all .* from the back of the string and cut ${var%%.*} :
Linuxpoison
------------------------------------------
Find first .* from the back of the string and cut ${var%.*} :
Linuxpoison.Linuxpoison

Using above concept you can rename all the files withing the directory having a particular ext (eg *.foo) to any other ext (eg *.boo), using something like ....
mv ${file} "${file%.foo}.boo"




0 comments:

Post a Comment

Related Posts with Thumbnails