在 bash 中连接字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2379533/
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 strings in bash
提问by Open the way
I have in a bash script:
我有一个 bash 脚本:
for i in `seq 1 10`
do
read AA BB CC <<< $(cat file1 | grep DATA)
echo ${i}
echo ${CC}
SORT=${CC}${i}
echo ${SORT}
done
so "i" is a integer, and CC is a string like "TODAY"
所以“i”是一个整数,CC是一个像“TODAY”这样的字符串
I would like to get then in SORT, "TODAY1", etc
我想进入SORT“TODAY1”等
But I get "1ODAY", "2ODAY" and so
但我得到“1ODAY”、“2ODAY”等等
Where is the error?
错误在哪里?
Thanks
谢谢
回答by tonio
You should try
你应该试试
SORT="${CC}${i}"
Make sure your file does not contain "\r" that would end just in the end of $CC. This could well explain why you get "1ODAY".
确保您的文件不包含以 $CC 结尾的“\r”。这可以很好地解释为什么你得到“1ODAY”。
Try including |tr '\r' '' after the cat command
尝试在 cat 命令之后包含 |tr '\r' ''
回答by ghostdog74
try
尝试
for i in {1..10}
do
while read -r line
do
case "$line" in
*DATA* )
set -- $line
CC=
SORT=${CC}${i}
echo ${SORT}
esac
done <"file1"
done
Otherwise, show an example of file1 and your desired output
否则,显示 file1 的示例和您想要的输出
回答by Charles Stewart
ghostdog is right: with the -r option, read avoids succumbing to potential horrors, like CRLFs. Using arrays makes the -r option more pleasant:
ghostdog 是对的:使用 -r 选项, read 避免屈服于潜在的恐怖,如 CRLF。使用数组使 -r 选项更令人愉快:
for i in `seq 1 10`
do
read -ra line <<< $(cat file1 | grep DATA)
CC="${line[3]}"
echo ${i}
echo ${CC}
SORT=${CC}${i}
echo ${SORT}
done

