sed是否可以在文本文件的分隔符之间添加字符?

问题描述 投票:0回答:2

我有一个看起来像这样的输入文件(customers.txt):

Name, Age, Email, 
Hank, 22, [email protected]
Nathan, 32, [email protected]
Gloria, 24, [email protected]

我试图输出到文件(customersnew.txt),使其看起来像这样:

Name: Hank     Age: 22   Email: [email protected]
Name: Nathan   Age: 32   Email: [email protected]
Name: Gloria   Age: 24   Email: [email protected]

到目前为止,我只能得到类似这样的输出:

Name: Hank, 22, [email protected]
Name: Nathan, 32, [email protected]
Name: Gloria, 24, [email protected]

我正在使用的代码是

sed -e '1d'\
    -e 's/.*/Name: &/g' customers.txt > customersnew.txt

我还尝试过使用-e 's/,/\n/g'\-e '2s/.*Age: &/g'分隔数据。没用任何帮助将不胜感激。

sed
2个回答
1
投票
$ awk 'BEGIN {FS=', ';OFS='\t'} NR==1 {split($0,hdr);next} {for(i=1;i<=NF;i++)$i=hdr[i]": "$i} 1' file Name: Hank Age: 22 Email: [email protected] Name: Nathan Age: 32 Email: [email protected] Name: Gloria Age: 24 Email: [email protected]

这只是将标头保存到数组中,并在后面的记录中将每个字段加<header>:


0
投票
awk ' BEGIN{ FS=", " OFS="\t" } FNR==1{ for(i=1;i<=NF;i++){ value[i]=$i } next } { for(i=1;i<=NF;i++){ $i=value[i] ": " $i } } 1 ' Input_file

说明:添加上述解决方案的说明。

awk ' ##Starting awk program from here. BEGIN{ ##Starting BEGIN section of this program from here. FS=", " ##Setting field separator as comma space here. OFS="\t" ##Setting output field separator as TAB here for all lines. } FNR==1{ ##Checking here if this is first line then do following. for(i=1;i<=NF;i++){ ##Starting a for loop to traverse through all elements of fields here. value[i]=$i ##Creating an array named value with index variable i and value is current field value. } next ##next will skip all further statements from here. } { for(i=1;i<=NF;i++){ ##Traversing through all fields of current line here. $i=value[i] ": " $i ##Setting current field value adding array value with index i colon space then current fiedl value here. } } 1 ##1 will print all lines here. ' Input_file ##Mentioning Input_file name here.

0
投票
#!/usr/bin/env bash count=0 max=$(wc -l < file.txt) while ((count < max)); do if ((count++ == 0 )); then IFS=, read -r name age email else IFS=, read -r real_name real_age real_email printf '%s: %-10s%s:%-6s %s:%s\n' "$name" "$real_name" "$age" "$real_age" "${email%,*}" "$real_email" fi done < file.txt
© www.soinside.com 2019 - 2024. All rights reserved.