shell - 将数据写入 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
解决方案
代码中的注释。剧本:
# 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
推荐阅读
- swift - 当响应数据不包含要使用 Combine 解码的对象时,我怎么能抛出错误?
- php - Symfony - 在 Bundle 内创建自己的配置(service.yaml)
- elasticsearch - Elasticsearch 通过增强和模糊搜索跨领域
- kubernetes - 单节点集群(minikube)上的 rook ceph 中出现 1 pg 过小健康警告
- angular - 如何更改角材料轮廓边框的大小?
- matlab - 使用 MATLAB 使用梯度下降进行逻辑回归的全局最小值
- graphql - 如何从 JWT 身份验证中排除 Quarkus Graphql-UI?
- swift - Swift - 计算属性与数据库操作
- python - 是否可以发出命令 !messages @user
- sql-server - 解析包含多列和子查询的查询返回超过 1 个值