'Extract a string between double quotes from the 6th line of a file in Unix and assign it to variable

Newbie to unix/shell/bash. I have a file name CellSite whose 6th line is as below:

    btsName = "RV74XC038",

I want to extract the string from 6th line that is between double quotes (i.e.RV74XC038) and save it to a variable. Please note that the 6th line starts with 4 blank spaces. And this string would vary from file. So I am looking for a solution that would extract a string from 6th line between the double quotes.

I tried below. But does not work.

str2 = sed '6{ s/^btsName = \([^ ]*\) *$/\1/;q } ;d' CellSite;

Any help is much appreciated. TIA.



Solution 1:[1]

sed is a stream editor.

For just parsing files, you want to look into awk. Something like this:

awk -F \" '/btsName/ { print $2 }' CellSite

Where:

  • -F defines a "field separator", in your case the quotation marks "
  • the entire script consists of:
  • /btsName/ act only on lines that contain the regex "btsName"
  • from that line print out the second field; the first field will be everything before the first quotation marks, second field will be everything from the first quotes to the second quotes, third field will be everything after the second quotes
  • parse through the file named "CellSite"

There are possibly better alternatives, but you would have to show the rest of your file.

Solution 2:[2]

Using sed

$ str2=$(sed '6s/[^"]*"\([^"]*\).*/\1/' CellSite)
$ echo "$str2"
RV74XC038

Solution 3:[3]

You can use the following awk solution:

btsName=$(awk -F\" 'NR==6{print $2; exit}' CellSite)

Basically, get to the sixth line (NR==6), print the second field value (" is used to split records (lines) into fields) and then exit.

See the online demo:

#!/bin/bash
CellSite='Line 1
Line 2
Line 3
    btsName = "NO74NO038",
Line 5
    btsName = "RV74XC038","
Line 7
    btsName = "no11no000",
'
btsName=$(awk -F\" 'NR==6{print $2; exit}' <<< "$CellSite")
echo "$btsName" # => RV74XC038

Solution 4:[4]

This might work for you (GNU sed):

var=$(sed -En '6s/.*"(.*)".*/\1/p;6q' file)

Simplify regexs and turn off implicit printing.

Focus on the 6th line only and print the value between double quotes, then quit.

Bash interpolates the sed invocation by means of the $(...) and the value extracted defines the variable var.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 SiKing
Solution 2
Solution 3 Wiktor Stribiżew
Solution 4 potong