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$