Shell command to retrieve specific value using pat

2019-03-06 12:02发布

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.

标签: bash shell awk sed
3条回答
我欲成王,谁敢阻挡
2楼-- · 2019-03-06 12:46

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
查看更多
Luminary・发光体
3楼-- · 2019-03-06 12:49

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

. filename.txt
echo $appid
查看更多
神经病院院长
4楼-- · 2019-03-06 13:00

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
查看更多
登录 后发表回答