Swati Singhal
Swati Singhal

Reputation: 21

Shell Script to read text File line by line and append to variable with a word in between

I have a text file like this:

abc:value
test:value

I want to read these line by line and append to a variable in my shell script and also add a custom string. So I want a variable that has: "Hello abc:value Hello test:value"

I used :

for line in $(cat $hdr_file)
do
    HDRS="-H $line"
    echo $HDRS  
    hdrtxt=$HDRS            
done
echo $hdrtxt

But $hdrtxt printed only has last line but does not retain other lines read from the file.

Upvotes: 0

Views: 2168

Answers (2)

agc
agc

Reputation: 8446

The variable $hdrtext is being overwritten with each run of the loop. To append to a shell variable, include the variable itself in each assignment:

unset hdrtxt
while read line
do
     HDRS="-H $line"
     echo $HDRS
     hdrtxt="$hdrtxt$HDRS"
done < $hdr_file
echo $hdrtxt

Output:

-H abc:value
-H test:value
-H test:value-H abc:value

Note: the $HDRS variable isn't necessary, and the in-loop echo seems merely diagnostic, so the code can be simplified:

unset hdrtxt
while read line
do
     hdrtxt="${hdrtxt}-H $line"
done < $hdr_file
echo $hdrtxt

Upvotes: 0

RomanPerekhrest
RomanPerekhrest

Reputation: 92884

First, don't read lines of file with for loop in shell/bash (it'll split on any whitespace (space, tab, newline) by default).
In your simple case it's enough to use printf + sed:

hdrtxt=$(printf "%s " $(sed 's/^/Hello /' "$hdr_file"))
echo "$hdrtxt" 
Hello abc:value Hello test:value

Upvotes: 1

Related Questions