以Formta格式将数据写入文件

时间:2019-05-30 11:37:32

标签: shell unix

我在文件1

中具有以下格式的数据
router.get("/my/url", async (req, res) => {
  // await code...
});

我所需的输出=>我需要使用以下格式

我想以此格式将数据写入 FILE 2

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

我的代码:

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

但是我的上述代码仅在File2.txt的前两行中打印

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

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

2 个答案:

答案 0 :(得分:1)

代码注释。脚本:

# 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

经过tutorialspoint

测试

答案 1 :(得分:0)

以下脚本将完成您想要的

#!/bin/bash
input="./file1.txt"
evenLine=0

# this will overwrite file2.txt
echo "Name|Age" > file2.txt

# loop over all lines
while IFS= read -r line
do
  if [ 0 -eq $evenLine ]
  then
    # -n to not append newline, remove string "Name: "
    echo -n "$line" | sed -e "s/Name: *//g" >> file2.txt
    evenLine=1
  else
    # replace "Age: " with " | "
    echo "$line" | sed -e "s/Age: */ | /g" >> file2.txt
    evenLine=0
  fi
done < "$input"