How can i read specific line and specific field using Bash?

3.9k views Asked by At

I have this file and i want to only get the value of testme= So that i can do another action. But this throws lots of lines and actually cant yet make it work.

1. test.sh

#!/bin/bash
for i in $(cat /var/tmp/test.ini); do
  # just one output i need: value1
  grep testme= $i 
done

2. /var/tmp/test.ini

; comments
testme=value1
; comments
testtwo=value2
5

There are 5 answers

1
Angelom On BEST ANSWER

How about

#!/bin/bash

grep 'testme=' /var/tmp/test.ini | awk -F= '{ print  $2 }'

or alternatively just using bash

#!/bin/bash

regex='testme=(.*)'

for i in $(cat /var/tmp/test.ini);
do
    if [[ $i =~ $regex ]];
    then
        echo ${BASH_REMATCH[1]}
    fi
done
0
John Kugelman On
grep -v '^;' /tmp/test.ini | awk -F= '$1=="testme" {print $2}'

The grep removes comments, then awk finds the variable and prints its value. Or, same thing in a single awk line:

awk -F= '/^\s*;/ {next} $1=="testme" {print $2}' /tmp/test.ini 
1
Paul Rubel On

How about this?

$ grep '^testme=' /tmp/test.ini  | sed -e 's/^testme=//' 
value1

We find the line and then remove the prefix, leaving only the value. Grep does the iterating for us, no need to be explicit.

0
Kent On

I checked your codes, the problem is in your for loop.

you actually read each line of the file, and give it to grep, which is NOT correct. I guess you have many lines with error,

no such file or directory

(or something like that).

you should give grep your file name. (without the for loop)

e.g.

grep "testme=" /var/tmp/test.ini
0
William Pursell On

awk is probably the right tool for this, but since the question does seem to imply that you only want to use the shell, you probably want something like:

while IFS== read lhs rhs; do
  if test "$lhs" = testme; then
     # Here, $rhs is the right hand side of the assignment to testme
  fi
done < /var/tmp/test.ini