Wednesday, January 11, 2012

split a string using 'tr' and convert into array

Below script reads a file line by line
Each line is a string delimited by underscore ( '_' ).Script splits each string by this delimiter and extracts the last index,which is the date part of the string
and produces a new string

if the lines of status.txt are

impression_1_10142011
impression_1_10152011

then output of the below script is

impression_2_10142011
impression_2_1015201
-----------------------------------------------------------
#!/bin/sh

filename="status.txt"

while read line
do
table=$line
splits=(`echo "$table" | tr '_' ' '`)
tabletmp=`echo "impression_2_""${splits[2]}"`
echo "table tmp=$tabletmp"
done < ${filename}

echo "over"

-------------------------------------------------------------

Other ways of splitting a string by delimiters
a.
>> echo "nitesh:kumar:jag:gita" | awk -F: '{print $3}'
>> jag

b.
>> echo "nitesh:kumar:jag:gita" | cut -d: -f4
>> gita

c.
>> echo "nitesh" | awk '{print substr($0,2)}'
>> itesh

d.
>> echo "nitesh" | cut -c2
>> i

e.
>> echo "nitesh" | cut -c2-
>> itesh

f.
>> echo "nitesh" | cut -c2,4
>> ie

g.
>> echo "nitesh" | cut -c2-4
>> ite

h.
>> df
Filesystem 1K-blocks Used Available Use% Mounted on
/dev/sda1 10321208 2687988 7108932 28% /
/dev/sdb 423135208 203084 401438084 1% /mnt
none 8963788 0 8963788 0% /dev/shm
/dev/sdg 1032123136 953849496 25844840 98% /data

then
>> df | grep "\ /data" | awk '{print $5}'
>> 98%

i. TO get process id of a process 'crond'
>> ps -ef | grep "crond" | grep -v grep | awk '{print $2}'
>> 988

No comments:

Post a Comment