samir samir - 1 year ago 92
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=;Public=;dsc-InterInstance=;dsc-OAM=
vm19_DSC_Instance_3 dsc-sig=;Public=;dsc-InterInstance=;dsc-OAM=

From this below name i want the number like 4 and 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

Answer Source

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 some task with "$i"

Mind the [ useless use of cat ]

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download