首页 > 解决方案 > 将数据写入 Formta Form 中的文件

问题描述

我在文件 1中有以下格式的数据

NAME :  Ram 
AGE :  12
NAME :  Rahul
AGE:  13
NAME:   Raj
AGE:   14

我想要的输出 => 在下面的格式中我需要

我想以下面的格式将数据写入文件 2 ,例如

NAME| AGE
Ram|12
Rahul|13
Raj|14

我的代码:

head -2 file1.txt | nl | tr '\n' '|' >> file2.txt

但是我上面的代码只在 File2.txt 的前两行打印

1 NAME : Ram | 2 AGE : 12|

它必须循环到最后并写入文件 2

标签: shellunix

解决方案


代码中的注释。剧本:

# input test file as provided by OP
cat <<EOF >file
NAME :  Ram 
AGE :  12
NAME :  Rahul
AGE:  13
NAME:   Raj
AGE:   14
EOF

# My first solution - a simple bash while read loop
echo "NAME|AGE"
while IFS=': ' read -r _ name && IFS=': ' read -r _ age; do
    echo "$name|$age"
done <file

# Second solution - some parsing + xargs
# first remove spaces, then substitue `:` for a space
# then run printf, don't print any NAME and AGE %.0s and print the names and ages %s
echo "NAME|AGE"
<file tr -d ' ' | tr ':' ' ' | xargs printf "%.0s%s|%.0s%s\n"

# Third solution - sed!
# first remove spaces and remove everything before :
# then read two lines, substitue newline for a | and print
echo "NAME|AGE"
<file sed 's/ //g; s/.*://' | sed 'N;s/\n/|/'

将输出:

NAME|AGE
Ram|12
Rahul|13
Raj|14
NAME|AGE
Ram|12
Rahul|13
Raj|14
NAME|AGE
Ram|12
Rahul|13
Raj|14

教程点测试


推荐阅读