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

Time:05-13

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.

CodePudding user response:

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.

CodePudding user response:

Using sed

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