将行拆分为多行,并在开头添加一个子字符串

时间:2018-07-20 20:03:00

标签: bash shell sed command-line

我对bash还是很陌生,并且有这样的日志:

10, "a@gmail.com"
2, "b@gmail.com"
3333, "c@hotmail.com", "d@gmail.com"
4, "e@hotmail.com", "f@hotmail.com", "g@gmail.com"
55, "h@gmail.com"

我希望是这样

10, "a@gmail.com"
2, "b@gmail.com"
3333, "c@hotmail.com"
3333, "d@gmail.com"
4, "e@hotmail.com" 
4, "f@hotmail.com" 
4, "g@gmail.com"
55, "h@gmail.com"

我如何在bash中做到这一点?

2 个答案:

答案 0 :(得分:2)

用于处理文本的标准UNIX工具是awk:

$ awk 'BEGIN{FS=OFS=", "} {for (i=2;i<=NF;i++) print $1, $i}' file
10, "a@gmail.com"
2, "b@gmail.com"
3333, "c@hotmail.com"
3333, "d@gmail.com"
4, "e@hotmail.com"
4, "f@hotmail.com"
4, "g@gmail.com"
55, "h@gmail.com"

答案 1 :(得分:0)

作为第一个参数,我将路径传递到文件。 如果不传递任何参数,我将说明错误并以(-1)退出。

我正在遍历文件,逗号改为空格。 每次迭代我都会用空格隔开。如果这个单词是数字,我将存储它并转到下一个单词。如果不是数字,我将打印前一个数字和当前单词,并用逗号分隔。在for循环之前,我将数字初始化为0,以防万一;)

#!/bin/bash                             

if [ -z "${1}" ]; then                  
    echo "No file specified"            
    exit -1                                
else                                    
    file=$1                             
    echo "Parsing file \"$file\":"      
fi                                      

number="0"                              

for word in $(sed "s@,@ @g" $file); do   
    if [[ $line =~ ^[0-9]+ ]] ; then    
        number=${word};                 
        continue;                       
    else                                
        echo "$number, ${word}"         
    fi                                  
done                                    
exit 0

运行:

test@LAPTOP-EQKIVD8A:~$ cat new.txt
10, "a@gmail.com"
2, "b@gmail.com"
3333, "c@hotmail.com", "d@gmail.com"
4, "e@hotmail.com", "f@hotmail.com", "g@gmail.com"
55, "h@gmail.com"
test@LAPTOP-EQKIVD8A:~$ ./script.sh  new.txt
Parsing file "new.txt":
10, "a@gmail.com"
2, "b@gmail.com"
3333, "c@hotmail.com"
3333, "d@gmail.com"
4, "e@hotmail.com"
4, "f@hotmail.com"
4, "g@gmail.com"
55, "h@gmail.com"