Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

I am having two file naming Extra_info and Class_info

Class_info contains data :

stuId stuName stuClass 
S01    jagdeep  First
S02    harsh    First
S03    Roop     Second
S04    Kali     Third

Extra_info contains extra information about student like

stuId stuCity stuEmail         stuPhone
S01    Sirsa  faltu@gmail.com  1234567890

I am getting result from both files using grep for stuId and displaying the result as:

res1=`grep $stuId $locDir/Class_info`
res2=`grep $stuId $locDir/Extra_info|cut -d" " -f2-` 
## also I tried res2=`grep $stuId $locDir/Extra_info|awk '{$1="" ; print $0}'`
echo $res1 $res2

Instead of displaying:

     S01 jagdeep First Sirsa  faltu@gmail.com  1234567890

It is displaying:

     Sirsa  faltu@gmail.com  1234567890

As I could think at the time of echo the variable res2 is nullifying result from res1.

Please, suggest the possible reason for this and please provide solution for the same.

share|improve this question
Works as expected for me. Have you checked if $res1 is getting correct output without print $res2? –  Ketan Feb 19 at 16:29
Very strange. I tried under zsh, same result: if I store the result of 2 consecutive grep in two variables and echo them, the first is not printed. If I only echo the first, it works. If the first is assigned the result of a ls instead of a grep, it works. So the problem could be related to grep outputs? I don't understand why. –  JPG Feb 19 at 16:44
@JPG I can confirm that it works under zsh on my system as expected, ie. the results of both greps are printed. –  Ketan Feb 19 at 16:46
add comment

2 Answers 2

Your input files probably have CR-NL line endings, so $res1 returns the cursor to the beginning of the line then then $res2 overwrites it. Run your files through dos2unix to fix that.

share|improve this answer
Yes, you got it! I am also working with a file with CR-NL, that's the reason. If I remove them, it works. –  JPG Feb 19 at 16:57
@glenn: Thanks for replying , I copied the sample content in new files and it worked. But the data is large so I have to work with same files. tried to find the suspicious extra character in the file, unable to find . Is there any command which could help to find out the culprit character –  Jagdeep Feb 20 at 9:19
od -c filename will display the \r prior to the \n –  glenn jackman Feb 20 at 12:06
@glennjackman : Thanks , I am able to find the character and replaced using tr command, It is working fine now. –  Jagdeep Feb 24 at 10:00
add comment
s=`grep jagdeep file1.txt |awk '{print $1}'`
egrep $s file2.txt
share|improve this answer
add comment

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.