Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
241 views
in Technique[技术] by (71.8m points)

linux - BASH using grep and awk inside a variable

bash-3.2$ FNAME=$1
bash-3.2$ OLD_NO=$(grep "_version=" | awk -F '"' '{print $12}' $FNAME)

Line 2 does not appear to be working for me. Am I not closing/quoting it correctly? It seems to hang

Updated the script to reflect below suggestions

echo $OLD_NO
OLD_NO=$(grep '_version=' "$FNAME" | awk -F '"' '{print $12}')
#Get the version of the
echo "What do you want to update release number to?"
REPLACEMENT="_version="$NEW_NO
echo $REPLACEMENT
sed -i ''s/$OLD_NO/$REPLACEMENT/g'' $FNAME

~

get a new error

bash-3.2$ ./vu reader.xml 

What do you want to update release number to?
_version=
sed: -e expression #1, char 0: no previous regular expression

Works in bash though

bash-3.2$ grep _version market_rules_cd.reader.xml | awk -F '"' '{print $12}'

14.8.21.1

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The line hangs because grep '_version=' will blocking wait on stdin since you didn't passed a file name argument. To stop it from hanging pass the file name to grep, not to awk. awk will then process grep's output:

OLD_NO=$(grep '_version=' "$FNAME" | awk -F '"' '{print $12}')

Btw: The job can be done with awk only, you don't need grep:

OLD_NO=$(awk -F '"' '/_version=/ {print $12}' "$FNAME")

Note that awk programs having the following form:

condition { action }  [; more of them ]

You can omit the condition if the action should apply to every line (this is widely used), however in this case you can use a regex condition to restrict the action only to lines containing _version=:

/_version=/ { print $12 }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...