2

I have a line of output with three quotes, and I specifically need to extract the second quote into a variable. So for example, with the command cmd | grep tokens, I get the following output:

Output

"abcde", "12345", "zyxwv"

I need to pull 12345 out of there. The closest I've gotten is by adding | cut '\"' -f2 to the command, but that returns "abcde". How can I get the second quote rather than the first?

2
  • where is this string coming from? it it possible that there will be quote-marks embedded in the strings?
    – Jasen
    Commented Jun 9, 2016 at 2:49
  • Is it possible that the might be unquoted strings in the input?
    – Kusalananda
    Commented Jan 23, 2017 at 13:49

3 Answers 3

2

Just improve your cut command. You're specifying the delimiter as " so count the fields before each ".

For example

Before the first " ther's nothing so:

$ echo "\"abcde\", \"12345\", \"zyxwv\"" | cut -d \" -f 1
[empty]

Before the second " is abcde

$ echo "\"abcde\", \"12345\", \"zyxwv\"" | cut -d \" -f2
abcde

Before the third " is ,

$ echo "\"abcde\", \"12345\", \"zyxwv\"" | cut -d \" -f3
, 

So your expected output will be the fourth one

$ echo "\"abcde\", \"12345\", \"zyxwv\"" | cut -d \" -f4
12345

I hope the escape backslash don't mess you

0

Is this what you are trying to achieve?

variable=$(cmd | grep tokens | cut -d',' -f 2 | sed 's/ //')
3
  • Not exactly but it does the trick. Thank you!! Commented Jun 8, 2016 at 19:49
  • This will print also the quotes, then you must make other sed substitution for those
    – tachomi
    Commented Jun 8, 2016 at 19:55
  • No it does not! I tried this echo Output tokens: "abcde", "12345", "zyxwv" | cut -d',' -f 2 | sed 's/ // and got 12345
    – Vombat
    Commented Jun 8, 2016 at 19:56
0

We can simply do it with awk

eg:

[user@test ~]$ echo "abcde", "12345", "zyxwv" | awk -F"," '{print $2}' 12345

if the output is coming from a cmd then

var='<cmd> | awk -F"," '{print $2}'

3
  • There are unbalanced quotes in the second command. And in the first command, awk actually receives unquoted input due to the way you pass it with echo.
    – Kusalananda
    Commented Jan 23, 2017 at 13:52
  • In the second command i actually want to add the quote which is in the tilde key but while posting it is not printing the actual quote.
    – upkar
    Commented Jan 23, 2017 at 13:54
  • It's better to use $( ... ) than backticks in any case.
    – Kusalananda
    Commented Jan 23, 2017 at 14:06

You must log in to answer this question.

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