samir samir - 2 months ago 11
Bash Question

Get a particular char in particular line and store in variable

I am having a file which contains 2 lines and i want to get the particular char from each line and do some operation.

My File:

vm16_DSC_Instance_4 dsc-sig=172.16.17.14;Public=10.10.72.15;dsc-InterInstance=172.16.18.14;dsc-OAM=172.16.16.19
vm19_DSC_Instance_3 dsc-sig=172.16.17.15;Public=10.10.72.14;dsc-InterInstance=172.16.18.15;dsc-OAM=172.16.16.20


Requirement:
From this below name i want the number like 4 and 3.

vm16_DSC_Instance_4
vm19_DSC_Instance_3


Current :
Here i am getting 4 and 3 in one shot. I want to take 4 from 1st line and do some operation then i will take 3 from 2nd line and will do some operation. Basically i want based on counter it will get the 1st or 2nd line char.

cat /tmp/tmp_inst_tmp |awk '{print $1}' | cut -d'_' -f4
4
3

Answer

Use an array to store the result and use sed for this simple task

array=( $(sed -E 's/^[^[:blank:]]*_([[:digit:]]+)[[:blank:]]+.*$/\1/' file) )
for i in "${array[@]}"
do
# Do some task with "$i"
done

Mind the [ useless use of cat ]

Comments