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?

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
#!/bin/bash
FILE=$1
while read line; do
number=$(echo "${line}" | awk 'gsub(" *","")$0~/type/{getline;print;exit}' RS=" ")
echo "${number}"
done < ${FILE}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.