首页 新闻 会员 周边

Linux脚本 while read line问题

0
悬赏园豆:100 [已解决问题] 解决于 2020-03-10 13:13

源文件里面有很多段落,每个段落之间都是以‘##**************##’隔开。

需要把每个段落分割成一个单独的文件。

遇到的问题是文件中的‘ *’会被替换成文件名(单独的星号不会替换,星号空格也不会替换,只有空格星号的时候才会被替换),请大神指点。

源文件:

[root@local]# cat test.logs
4567890 *
##*************************************##
rtyuio**tyuio432
##*************************************##
*rtyuiop*2* yuiop
##*************************************##
rtyuiop(3 * 4)iuytr
##*************************************##
8765432
[root@local]#

 

脚本:

[root@local]# cat read.sh
#!/bin/sh
logsname=test.logs
i=100
while read line
do
if [[ $line =~ '##' ]];then
((i++))
else
echo $line >> $i.txt
fi
done < "${logsname}"
[root@local]#

 

输出:

[root@local]# ll
total 28
-rw-r--r--. 1 root root 25 Mar 10 19:13 100.txt
-rw-r--r--. 1 root root 17 Mar 10 19:13 101.txt
-rw-r--r--. 1 root root 18 Mar 10 19:13 102.txt
-rw-r--r--. 1 root root 59 Mar 10 19:13 103.txt
-rw-r--r--. 1 root root 8 Mar 10 19:13 104.txt
-rwxr-xr-x. 1 root root 204 Mar 10 19:10 read.sh
-rw-r--r--. 1 root root 241 Mar 10 19:13 test.logs
[root@local]# cat *.txt
4567890 sample test.logs
rtyuio**tyuio432
*rtyuiop*2* yuiop
rtyuiop(3 100.txt 101.txt 102.txt sample test.logs 4)iuytr
8765432
[root@local]#

Robin_Wang的主页 Robin_Wang | 初学一级 | 园豆:20
提问于:2020-03-10 12:03
< >
分享
最佳答案
0

给变量加上引用. 不然替换结果会再次进行展开

收获园豆:100
jakio6 | 小虾三级 |园豆:1318 | 2020-03-10 12:32

可以在脚本里加上

set -x
set -v

来看到底执行了什么

jakio6 | 园豆:1318 (小虾三级) | 2020-03-10 12:36

@jakio6: 

修改了脚本如下,还是一样的问题。

do
set -x
set -v
if [[ "$line" =~ '##' ]];then

 

 

运行结果:

+ set -v
+ [[ 4567890 * =~ ## ]]
+ echo 4567890 100.txt 101.txt 102.txt 103.txt 104.txt sample test.logs
+ read line
+ set -x
+ set -v
+ [[ ##*************************************## =~ ## ]]
+ (( i++ ))
+ read line
+ set -x
+ set -v
+ [[ rtyuio**tyuio432 =~ ## ]]
+ echo 'rtyuio**tyuio432'
+ read line
+ set -x
+ set -v
+ [[ ##*************************************## =~ ## ]]
+ (( i++ ))
+ read line
+ set -x
+ set -v
+ [[ *rtyuiop*2* yuiop =~ ## ]]
+ echo '*rtyuiop*2*' yuiop
+ read line
+ set -x
+ set -v
+ [[ ##*************************************## =~ ## ]]
+ (( i++ ))
+ read line
+ set -x
+ set -v
+ [[ rtyuiop(3 * 4)iuytr =~ ## ]]
+ echo 'rtyuiop(3' 100.txt 101.txt 102.txt 103.txt 104.txt sample test.logs '4)i uytr'
+ read line
+ set -x
+ set -v
+ [[ ##*************************************## =~ ## ]]
+ (( i++ ))
+ read line
+ set -x
+ set -v
+ [[ 8765432 =~ ## ]]
+ echo 8765432
+ read line

Robin_Wang | 园豆:20 (初学一级) | 2020-03-10 12:53

@Robin_Wang: echo 那里

#!/bin/sh
set -v
set -x
logsname=test.logs
i=100
while read line
do
    if [[ $line =~ '##' ]];then
        ((i++))
    else
        echo "$line" >> $i.txt
    fi
done < "${logsname}"
jakio6 | 园豆:1318 (小虾三级) | 2020-03-10 13:05

@jakio6: 

谢谢!!

Robin_Wang | 园豆:20 (初学一级) | 2020-03-10 13:13
其他回答(1)
0
wengle | 园豆:567 (小虾三级) | 2020-03-10 14:40
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册