简体   繁体   English

如何在bash脚本中删除换行符?

[英]How can I delete a newline character in bash script?

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? 我的问题是,如何消除前两行之间的换行符?

Do it correctly in the first place. 首先要正确地做到这一点。

while read permission rest
do
  ...
done < adminpermission.txt

Also, heredocs. 此外,heredocs。

尝试:

$(echo $i | tr -d "\n" | cut -f1)

Have you checked if your your adminpermission.txt contains DOS style carriage returns? 您是否检查过您的adminpermission.txt包含DOS样式回车? Your code will strip linefeeds, but depending on how you view the output, carriage returns can break the lines like you describe. 您的代码将删除换行符,但根据您查看输出的方式,回车符可能会破坏您描述的行。

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,然后再次运行您的脚本。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM