1

I have a simple bash script that reads lines from a text file like so:

#!/bin/bash
FILE=$1
while read line; do

done < $FILE

I would like to match text between the string "-type " and a space, so in my line I have:

 random text -type 53 random text

I just want to extract "53" and assign it to the variable type_number. Which of these tools cut, sed, grep or awk would be appropriate for such task?

3 Answers 3

1
using sed -

echo "abcd 1234 -type 53 efgh 5678" |sed -r 's/^.*-type\s+([0-9]+).*$/\1/'
53

replace the line used here with $line and assign to a variable

0
#!/bin/bash
FILE=$1
while read line; do
type_number=`echo $line |awk '{for(i=1;i<=NF;i++){if($i=="-type")print $(i+1)}}'`
#here you can use your $type_number
done < $FILE
0
0
#!/bin/bash
FILE=$1
while read line; do
number=$(echo "${line}" | awk 'gsub(" *","")$0~/type/{getline;print;exit}' RS=" ")
echo "${number}"
done < ${FILE}

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .