bash 如何删除bash脚本中的换行符?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14490513/
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
How can I delete a newline character in bash script?
提问by user2005580
I have a little problem with a small script. The textfile has a lot of entries like:
我有一个小脚本的小问题。文本文件有很多条目,例如:
permission-project1-admin
permission-project2-admin
....
The script looks like this (indeed, it is an awful one but still helps me):
脚本看起来像这样(确实,这是一个糟糕的脚本,但仍然对我有帮助):
#!/bin/bash
for i in $(cat adminpermission.txt); do
permission=$(echo $i | cut -f1)
printf "dn:$permission,ou=groups,dc=domain,dc=com \n"
printf "objectclass: groupOfUniqueNames \n"
printf "objectclass: top \n"
printf "description: \n"
printf "cn:$permission \n\n"
done
The output looks fine, but because the textfile has a newline character at the end, the first line of printf is devided into two lines like:
输出看起来不错,但因为文本文件的末尾有一个换行符,所以 printf 的第一行被分成两行,如:
dn:permission-project1-admin
,ou=groups,dc=domain,dc=com
objectclass: groupOfUniqueNames
objectclass: top
description:
cn:permission-project1-admin
My question is, how I can eliminate the newline character between the first two lines?
我的问题是,如何消除前两行之间的换行符?
回答by Ignacio Vazquez-Abrams
Do it correctly in the first place.
while read permission rest
do
...
done < adminpermission.txt
Also, heredocs.
此外,heredocs。
回答by Simon Dirmeier
Try:
尝试:
$(echo $i | tr -d "\n" | cut -f1)
回答by that other guy
Have you checked if your your adminpermission.txtcontains DOS style carriage returns? Your code will strip linefeeds, but depending on how you view the output, carriage returns can break the lines like you describe.
您是否检查过您的adminpermission.txt包含 DOS 样式的回车符?您的代码将去除换行符,但根据您查看输出的方式,回车可能会像您描述的那样断行。
You can try
你可以试试
mv adminpermission.txt backup.txt
tr -d '\r' < backup.txt > adminpermission.txt
to convert to UNIX EOL, and then run your script again.
转换为 UNIX EOL,然后再次运行您的脚本。

