连接 grep 输出字符串(bash 脚本)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15462575/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Concatenate grep output string (bash script)
提问by jensG
I'm processing some data from a text file using a bash script (Ubuntu 12.10).
我正在使用 bash 脚本(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.
基本思想是我使用 grep 从文件中选择某一行。接下来,我处理该行以使用 sed 获取数字。grep 和 sed 命令都在工作。我可以回应这个数字。
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.
当我从变量或文件执行 grep 命令时,组合字符串时得到不同的结果。当我 grep 文件时,连接出错。当我使用与文件中相同的文本 grep 变量时,它按预期工作。
What am I doing wrong with the grep from a file?
我对文件中的 grep 做错了什么?
Contents of test.pdb
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
采纳答案by Salvatore
I went crazy with the same issue.
我对同样的问题发疯了。
The real problem is that your "test.pdb" has probably a wrong EOL (end of line) character.
真正的问题是您的“test.pdb”可能有错误的 EOL(行尾)字符。
Linux EOL: LF (aka \n)
Linux EOL:LF(又名 \n)
Windows EOL: CR LF (aka \r \n)
Windows EOL:CR LF(又名 \r \n)
This mean that echo and grep will have problem with this extra character (\r), luckily tr, sed and awk manage it correctly.
这意味着 echo 和 grep 会遇到这个额外字符 (\r) 的问题,幸运的是 tr、sed 和 awk 正确管理它。
So you can try also with:
所以你也可以尝试:
DATA=$(grep 'overall' test.pdb | sed -n -e "s/^.*= //p" | sed -e 2s/\r$//")
DATA=$(grep '整体' 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')
DATA=$(grep '整体' test.pdb | sed -n -e "s/^.*= //p" | tr -d '\r')
回答by Amir Afghani
Try this:
尝试这个:
SUFFIX=";0"
DATA="${DATA}${SUFFIX}"

