0

I have a file which contains data like below.

appid=TestApp
version=1.0.1

We want to parse the file and capture the value assigned to appid field.

I have tried with awk command as below

awk '/appid=/{print $1}' filename.txt

However it outputs the whole line

appid=TestApp 

but we required only

TestApp

Please let me know how I can achieve this using awk/grep/sed shell commands.

The Archetypal Paul
  • 41,321
  • 20
  • 104
  • 134
patel kavit
  • 484
  • 1
  • 6
  • 22

3 Answers3

4

You need to change the field separator:

awk -F'=' '$1 ~ /appid/ {print $2}' filename.txt

or with an exact match

awk -F'=' '$1 == "appid" {print $2}' filename.txt

outputs

TestApp
martin
  • 3,149
  • 1
  • 24
  • 35
3

There's about 20 different ways to do this but it's usually a good idea when you have name = value statements in a file to simply build an array of those assignments and then just print whatever you care about using it's name, e.g.:

$ cat file
appid=TestApp
version=1.0.1
$
$ awk -F= '{a[$1]=$2} END{print a["appid"]}' file
TestApp
$ awk -F= '{a[$1]=$2} END{print a["version"]}' file
1.0.1
$ awk -F= '{a[$1]=$2} END{for (i in a) print i,"=",a[i]}' file
appid = TestApp
version = 1.0.1
Ed Morton
  • 188,023
  • 17
  • 78
  • 185
0

If you are in the shell already then simply sourcing the file will let you get what you want.

. filename.txt
echo $appid
Etan Reisner
  • 77,877
  • 8
  • 106
  • 148
  • 1
    You should not recommend sourcing files, you never now what is hidden, see the explanation [here](http://stackoverflow.com/questions/16260165) – martin Aug 21 '14 at 12:14
  • Sourcing random files is certainly not safe. I wouldn't recommend using a file like that for user config either. But neither of those is the same as saying that in known processes one shouldn't source files. – Etan Reisner Aug 21 '14 at 12:18
  • Yes, that's also why I didn't downvote, because it probably works perfectly fine in this situation. – martin Aug 21 '14 at 12:20
  • Right and a useful warning to add. – Etan Reisner Aug 21 '14 at 13:06