Extract substring from a bash line with a Pattern

Asked

Viewed 149 times

0

Good afternoon to all,

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

 11Sala                                    1:4     FF

The first column has the ID, and the second has the data I want to get (1:4), but when I have lines in that identification, for example has room, Sala1, sala2, I pick up all the lines and 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

'Sala1' on the second line

'Sala2' on the third line

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

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

How to do?

  • What is the expected result?

1 answer

0

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

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

And you just 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: To 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
  • 1

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

  • 1

    @fedorqui Boa! That’s what I was talking about! :)

  • Geek style? :/

Browser other questions tagged

You are not signed in. Login or sign up in order to post.