Shashikant shah

Monday 13 July 2015

ARRAY Details

$ cat arraymanip.sh
#! /bin/bash
Unix[0]='Debian'
Unix[1]='Red hat'

echo ${Unix[1]}

$./arraymanip.sh
Red hat
====================
declare -a Unix=('Debian' 'Red hat')
echo {unix[@]}
#./t.sh
Debian Red hat
==================

declare -a shashi=('jk'' 'gol 'hello');

echo ${shashi[0]}

#./script.sh

jk
====================
Unix=('Debian' 'Red hat' 'Ubuntu' 'Suse' 'Fedora' 'UTS' 'OpenLinux');

echo ${#Unix[@]} #Number of elements in the array
echo ${#Unix}  #Number of characters in the first element of the array.i.e Debian
echo ${#unix [1]} # length of the element located at index.
echo ${unix[@]:1:3} # remove the sentense in one line.e.g:- remove sentense 1 & 3
echo ${unix[2]:1:2} # remove the word in sentance.
echo ${unix[@]/ubuntu/sco unix} # ubuntu ko replace karega.
echo ${#unix[*]} # last file name.

unset unix[1] #1 is not showing.
unset Unix    # unix array not showing
================
$cat arraymanip.sh
Unix=('Debian' 'Red hat' 'Ubuntu' 'Suse' 'Fedora' 'UTS' 'OpenLinux');
Unix=("${Unix[@]}" "AIX" "HP-UX")
echo ${Unix[7]}

$./arraymanip.sh
AIX

========================
diff_file
file1
file2
file3

#!/bin/bash
file=`cat "diff_file"`
for t in ${file[@]}
    do
echo $t
    done
echo "read file content!"

#./script.sh
file1
file2
file3

=======================

#!/bin/bash
# define file array
files=(/etc/*)

# find total number of files in an array
echo "Total files in array : ${#files[*]}"
total=${#files[*]}

# Print 1st file name
echo "First filename: ${files[0]}"
echo "Second filename: ${files[1]}"
echo "Third filename: ${files[1]}"

# total - 1 = last item (subscript) in an array
echo "Last filename: ${files[$(( $total-1 ))]}"

echo
echo "****************"
echo "*** For Loop ***"
echo "****************"

# Use for loop iterate through an array

# $f stores current value

for f in "${files[@]}"
do
    echo -n "$f "
done

echo
echo
echo "**************************"
echo "*** C Style For Loop ****"
echo "**************************"
echo
# Use c style for loop
# get total subscripts in an array
total=${#files[*]}
#
for (( i=0; i<=$(( $total -1 )); i++ ))
do
    echo -n "${files[$i]} "
done

echo

=======================close======================================
cat file
2012/05/21
2012/05/22

vim test.sh

OLDIFS=$IFS
IFS="/"
while read f1 f2 f3
do
    echo "Year is : $f1"
    echo "Month is : $f2"
    echo "Date is : $f3"
done < file
IFS=$OLDIFS

./test.sh
Year is : 2012
Month is : 05
Date is : 21

Year is : 2012
Month is : 05
Date is : 22

====================================
# bash -c 'set w x y z; IFS=":-;"; echo "$*"' 
 
# w:x:y:z

No comments:

Post a Comment