Extract multiple values into corresponding variables

Here is my input

# MANIFEST.MF
Manifest-Version: 1.0
Build-Jdk: 1.6.0
Built-By: CM_TEAM
Build_SvnRev: 662789
Build_Number: 13.0.0.0-JDK8
Build_Date: Wed 04/05/2017-20:48:19.17
Archiver-Version: Plexus Archiver
Created-By: Apache Maven 3.1.0

Here is the expected output:

13.0.0.0-JDK8,04/05/2017-20:48:19.17,662789

Here the code I have to get above output.

out=$(cat MANIFEST.MF | tr -d '\r' | grep '^Build_'); 
BN=$(echo "$out" | grep Build_Number| awk '{print $NF}'); 
BS=$(echo "$out" | grep Build_SvnRev | awk '{print $NF}');
BD=$(echo "$out" | grep Build_Date | awk '{print $NF}');  
echo "$BN,$BD,$BS"

Is there a way that we can do this efficiently without having to repeat grep/awk multiple times? may be perl/awk can do that?

Hi, try:

awk '{A[$1]=$NF} END{print A["Build_SvnRev:"], A["Build_Number:"], A["Build_Date:"]}' OFS=, file

--
If there are CR (Windows) characters in the input file you could:

awk '{sub(/\r$/,x); A[$1]=$NF} END{print A["Build_SvnRev:"], A["Build_Number:"], A["Build_Date:"]}' OFS=, file
1 Like

That is awesome.. works great.

You said you wanted to "Extract multiple values into corresponding variables". Depending on your shell, this might work:

IFS=, read BN BD BS <<< $(awk '{A[$1]=$NF} END{print A["Build_SvnRev:"], A["Build_Number:"], A["Build_Date:"]}' OFS=, file)
echo "$BN,$BD,$BS"
662789,13.0.0.0-JDK8,04/05/2017-20:48:19.17
1 Like

With shell builtins

while IFS=": " read key val
do
  val=${val%$'\r'}
  case $key in
  Build_Number) BN=$val;;
  Build_SvnRev) BS=$val;;
  Build_Date) BD=$val;;
  esac
done < file
echo "$BN,$BD,$BS"

The code to strip the DOS-CRs works in bash and zsh

1 Like