4

I'm processing some data from a text file using a bash script (Ubuntu 12.10).

The basic idea is that I select a certain line from a file using grep. Next, I process the line to get the number with sed. Both the grep and sed command are working. I can echo the number.

But the concatenation of the result with a string goes wrong.

I get different results when combining string when I do a grep command from a variable or a file. The concatenation goes wrong when I grep a file. It works as expected when I grep a variable with the same text as in the file.

What am I doing wrong with the grep from a file?

Contents of test.pdb

REMARK overall = 324.88  
REMARK bon     = 24.1918  
REMARK coup    = 0  

My script

#!/bin/bash

#Correct function
echo "Working code"
TEXT="REMARK overall = 324.88\nREMARK bon     = 24.1918\nREMARK coup    = 0\n"
DATA=$(echo -e $TEXT | grep 'overall' | sed -n -e "s/^.*= //p" )

echo "Data: $DATA"
DATA="$DATA;0"
echo $DATA


#Not working
echo ""
echo "Not working code"
DATA=$(grep 'overall' test.pdb | sed -n -e "s/^.*= //p")

echo "Data: $DATA"
DATA="$DATA;0"
echo $DATA

Output

Working code
Data: 324.88
324.88;0

Not working code
Data: 324.88
;04.88
1

3 Answers 3

2

I went crazy with the same issue.

The real problem is that your "test.pdb" has probably a wrong EOL (end of line) character.

Linux EOL: LF (aka \n)

Windows EOL: CR LF (aka \r \n)

This mean that echo and grep will have problem with this extra character (\r), luckily tr, sed and awk manage it correctly.

So you can try also with:

DATA=$(grep 'overall' test.pdb | sed -n -e "s/^.*= //p" | sed -e 2s/\r$//")

or

DATA=$(grep 'overall' test.pdb | sed -n -e "s/^.*= //p" | tr -d '\r')

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

Comments

0

With , it will be more reliable and cleaner I guess :

$ awk '$2=="overall"{print "Working code\nData: " $4 "\n" $4 ";0"}' file.txt
Working code
Data: 324.88
324.88;0

2 Comments

It is an simpler way, but I get the same output with your command as with the grep command "Working code Data: 324.88 ;04.88". The concatenation occurs in the beginning, not at the end.
This didn't fix the problem, but it helped me a lot. Apparently the problem is local to my PC.
0

Try this:

SUFFIX=";0"
DATA="${DATA}${SUFFIX}"

1 Comment

This works on normal strings, but not with the output of grep/sed command. I don't know why.

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.