0

When I use sed to find some lines in a file, and then use for loop to do other things. I find there's a "\r" in the end of sed reuslt. So I have to use slice like ${var: 0: -1} to remove the "\r".

I think it's not reasonable, and the high probability is my own reason. So, can you help me to find the problem?

My environment:

Kernel: 5.15.0-56-generic x86_64 
bits: 64 
Distro: Ubuntu 20.04.2 LTS (Focal Fossa) 
shell: zsh

My bash script:

  • The problem is in echo `count_items_in_segment $seg`
#!/bin/bash

input_file="my.config"


function get_all_segment
{
    echo `sed -n -E -e "/\[.*\]/p" $input_file | sed -E -e "s/\[|\]//g"`
}

function count_items_in_segment
{
    sed -n "/\[$1\]/,/\[.*\]/p" $input_file | sed -n -E -e "/^#/d" -e "/^\s+$/d" -e "/\[.*\]/d" -e "p" | wc -l
}

index=1
for seg in `get_all_segment`
do 
    echo "$index: $seg"
    echo `count_items_in_segment $seg`
    ((index++))
done


printf `get_all_segment`

my.config

[client]
database =  test
user =  test
password = pwd
default-character-set = utf8
host = 192.168.0.1
port = 3306
# comment

[client1]
database =  test
default-character-set = utf8
host = 192.168.0.1
port = 3306

[client2]
database =  test
user =  test
default-character-set = utf8
host = 192.168.0.1
port = 3306
[client3]
database =  test

I have made sure there is a "\n" in the end of line.

Like this

cat my.config | sed -n -e "/\[.*\]/p" > test.txt
cat test.txt -A

The result is

  • In cat -A , ^M represents \r
[client]^M$
[client1]^M$
[client2]^M$
[client3]^M$
L.J.Zeng
  • 23
  • 5
  • Did you edit the source file, for example `my.config`, under Windows? – Geno Chen Dec 06 '22 at 06:11
  • 1
    You may use `dos2unix`. – Geno Chen Dec 06 '22 at 06:11
  • Amzing! I have considered this problem, but not have a try. Because I got the word in the middle of sentences, not the end of sentencs. But when I try your method, it solved it. Thanks a lot!! XD @GenoChen – L.J.Zeng Dec 06 '22 at 06:22
  • There is nothing in your code which would add a CR. The CR must have been there already before, and _sed_ did not remove it. – user1934428 Dec 06 '22 at 08:10

0 Answers0