Home > other >  Extract a text from a line or string using shell script
Extract a text from a line or string using shell script

Time:05-27

I have below data in my text file. I know how to loop through the line in shell script. Just need help in understanding how will I take out only ABC or TES or HYJ or VVB line by line from the below strings in a file.

!abc { xyz: "ABC", queue: "TEST" },
!abc { xyz: "TES", queue: "TEST" },
!abc { xyz: "HYJ", queue: "TEST" },
!abc { xyz: "VVB", queue: "TEST" },

The format of the above data will remain same..

I have tried this below suggestion

#!/bin/bash

line1="!abc { xyz: "ABC", queue: "TEST" },"
echo $line1
test_data=$(echo $line1 | grep -Eoh '!abc { xyz: ".*?"' | cut -d\" -f3)
echo $test_data

For the above code nothing is getting outputted.

Expected Output should be test_data = ABC If we do "echo $test_data" it should give me ABC

CodePudding user response:

Good day,

how about the cut command: $cut -d'"' -f2 file.txt

which cut out the second field with delimiter '"' .

CodePudding user response:

There are multiple ways of doing this, here is one, that is really simple:

  1. cat file.txt prints out the contents of the file

  2. AWK is used to divide the line into two parts, one prior to ":" and another one after it.

  3. Another AWK command is being used to divide the resulting output into two parts again, one before "," and one after it

  4. Lastly SED command is used to remove the double quotes ""

    cat file.txt | awk -F ":" '{print $2}' | awk -F "," '{print $1}' | sed -e 's/"//' -e 's/"$//'

  • Related