简体   繁体   中英

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:

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.

尝试:

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

Have you checked if your your adminpermission.txt contains 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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