【问题标题】:bash line Iteration in script脚本中的 bash 行迭代
【发布时间】:2023-03-20 10:50:01
【问题描述】:

我在文本文件中有以下数据

INSTANCES machine1    
Name    Berlin
Role    NA
INSTANCES  machine2   
Name    London
Role    NA
INSTANCES machine3       
Role    parser
Name    Dublin
INSTANCES machine4       
Name    Madrid
INSTANCES machine5
Role    parser
Name    Lisbon

我需要创建以下输出。我该怎么做

machine1    Berlin    NA
machine2    London    NA
machine3    Dublin    parser
machine4    Madrid    NONE
machine5    Lisbon    parser

【问题讨论】:

  • 使用 Linux 上可用的许多程序中的任何一种。您可能已经安装了 awk、sed 和 perl。这些可用于基本的文本操作。
  • processing 标签只能用于处理语言相关的问题。

标签: bash text iteration


【解决方案1】:

应该这样做:

#!/bin/bash
count=0
while read -r line; do
arr=($line)
if [[ $line == *INSTANCES* ]]; then
[[ $count != 0 ]] && new+="\n"${arr[1]} || new+=${arr[1]}
else
new+=" ${arr[1]}"
fi
((count++))
done <file
new+="\n"
printf "$new"

file 是文本文件名

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-03-06
    • 2010-09-20
    • 2023-01-13
    • 2018-09-07
    • 1970-01-01
    • 2020-10-22
    相关资源
    最近更新 更多