Extract substring from a line in bash with a pattern

0

Good afternoon everyone,

I have a text file with several rows with fixed columns:

 11Sala                                    1:4     FF

The first column has the ID, and the second one has the data I want to get ( 1:4 ), but when I have lines where the ID, for example has room, room1, room2, I get all the lines and I do not want .

I want to pick up the digits before the colon (:) and then 1 and 4

I'm using this code:

the variable CL contains:

'Room' on the first line

'Room1' on the second line

'Room2' on the third line

 declare -i TblStart=$(awk -F, "/$CL/ { print substr(\
 11Sala                                    1:4     FF
,48,10) }" /home/ficheiro.txt | cut -d ":" -f 1) declare -i TblEnd=$(awk -F, "/$CL/ { print substr(\
 declare -i TblStart=$(awk -F, "/$CL/ { print substr(\%pre%,48,10) }" /home/ficheiro.txt | cut -d ":" -f 1)

 declare -i TblEnd=$(awk -F, "/$CL/ { print substr(\%pre%,48,10) }" /home/ficheiro.txt | cut -d ":" -f 2)
,48,10) }" /home/ficheiro.txt | cut -d ":" -f 2)

How to do it?

    
asked by anonymous 16.03.2018 / 14:11

1 answer

0

I do not know if I understand very well, but supposing the file has the format:

Sala                                    1:4     FF
Sala1                                   2:5     FF
Sala2                                   3:6     FF

And you only want the numbers in the second column:

#!/bin/bash

while read line; do

  start=$(echo $line | awk -F " " '{print $2}' | awk -F ":" '{print $1}')
  end=$(echo $line | awk -F " " '{print $2}' | awk -F ":" '{print $2}')

  echo $start
  echo $end

done < ficheiro.txt

Note: You can improve the script ...

EDIT

As suggested by @fedorqui, a one-line solution (geek style):

awk '{split($2, a, ":"); print a[1]; print a[2]}' ficheiro.txt
    
16.03.2018 / 14:34