country code file contains some county code on line basis, seperated with commas.
Here after executing the script, only last country code is replacing with its country name. And if I change > (overwriting) to >> (appending) then same contents, multiple times with changes are appending to output file. I request you to suggest a solution for this.
And my second concern is that I have to append the name of the file at the end of each line, which I hav done using the commented line. Request you to suggest to perform both actions at a stretch.
First off, it would have been nice to show at least some sample lines from country_code.txt, which you read in. It is hard to predict what your code is doing when one is missing the input data it works on.
Second, you should write your code in an understandable way. You concatenate keywords (which isn't allowed at all), have several commands in one line without separating them by semicolons (which isn't allowed either) and don't indent properly (which is allowed, but makes it overly hard to read):
#!/bin/bash#
TFILE="/tmp/vinay/testb_1.txt"
while read line ; do
aline="$line"
echo $aline
code=`echo $aline|cut -d ',' -f1`
country=`echo $aline|cut -d ',' -f 2`
sed "s/$code/$country/g" testb_1.txt>testb_1.txt
sed 's/$/| testb_1.txt/g' "$TFILE" > "output1.txt"
echo $code
echo $country
done < country_code.txt
Third you should indeed use ">>" instead of ">", otherwise your output file will be overwritten with every pass of the loop. Anyhow, a lot of your loop is absolutely superfluous. The variable "aline" is not needed at all. Additionally you are writing to the input file "sed" reads from (for which you define a variable but never use it), which is not forbidden, but will not give the results you want:
#!/bin/bash#
TFILE="/tmp/vinay/testb_1.txt"
while read line ; do
echo $line
code="$(echo $line|cut -d ',' -f1)"
country="$(echo $line|cut -d ',' -f2)"
sed "s/$code/$country/g" "$TFILE" >> "${TFILE}".new
sed 's/$/| testb_1.txt/g' "$TFILE" >> "output1.txt"
echo $code
echo $country
done < country_code.txt
I still don't get the meaning of the second sed-statement, because several passes of the loop will add "| testb_1.txt" to the end of each line.
Just in case you have a list of country-codes and what to replace them by the countries names, your code won't do it anyhow:
#!/bin/bash
TFILE="/tmp/vinay/testb_1.txt"
cat country_code.txt | while read line ; do
code="$(echo "$line" | cut -d ',' -f1)"
country="$(echo "$line" | cut -d ',' -f2)"
sed 's/'"$code"'/'"$country"'/g' "$TFILE" > "${TFILE}".tmp
mv $"${TFILE}.tmp" "$TFILE"
echo LINE=${line} CODE=${code} COUNTRY=${country}
done
sed 's/$/| testb_1.txt/g' "$TFILE" > "output1.txt"
I won't expand on the recurring theme of replacing the "echo ... | cut ..." with simple shell variable expansions, i suppose this is enough for one session to devour.