1

I have a file in my file system. I want to read that file in bash script. File format is different i want to read only selected values from the file. I don't want to read the whole file as the file is very huge. Below is my file format:

Name=TEST
Add=TEST
LOC=TEST

In the file it will have data like above. From that I want to get only Add date in a variable. Could you please suggest me how I can do this.

As of now i am doing this to read the file:

file="data.txt"
while IFS= read line
do
    # display $line or do somthing with $line
    echo "$line"
done < "$file"

2 Answers 2

4

Use the right tool meant for the job, Awk in this case to speed things up!

dateValue="$(awk -F"=" '$1=="Add"{print $2; exit}' file)"
printf "%s\n" "dateValue"
TEST

The idea is to split input lines by = as the de-limiter. The awk logic works by checking the $1 field which equals to Add and prints the corresponding value associated with it.

The exit part after print is optional. It will quit the processing as soon as the Add string is met. It will help in quick processing if the file is huge as you have indicated.

Sign up to request clarification or add additional context in comments.

2 Comments

Is exit really optional?
@codeforester: optional as in, the command will still work as long as there are no similar $1 values in Add. But in a case if it is not present, the command will take too much time to run on a big file, but nevertheless will do the job.
2

You could rewrite your loop this way, notice the break after you got your line:

while IFS='=' read -r key value; do
  if [[ $value == "Add" ]]; then
    # your logic
    break
  fi
done < "$file"

If your intention is to just get the very first occurrence of "Add=", then you could use grep this way:

value=$(grep -m 1 '^Add=' "$file" | cut -f2 -d=)

1 Comment

Appreciate your answering in bash, but it is not really a tool for processing when considering performance, read through unix.stackexchange.com/questions/169716/… for a detailed/well-explained research on this

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.