dreamchaser1024
dreamchaser1024

Reputation: 45

How do I organize a list into a specifically formatted column in bash?

I'm working on a script where I need to organize some output into columns by line number. So Line number 5 needs to go to line number 1, line number 6 needs to go to line number 2 etc.

There is not really a pattern between the output to tell which one should be moved. The output is always the same, but just puts line breaks after every word, and lists the category names first, then the data after. Below I have some example code, along with what the output looks like. Thank you for your help!

while :
do
    read -r -p ""${LINK}" ---> " LOOP
    case "${LOOP}" in
       
      1) command | tr ',' '\n' | tr -d '"' | printf '1m11\n,p\n'
      2) another command
      3) blah blah
    esac
done

When running command 1, it outputs something like so (0 spaces in between)

CategoryA  
CategoryB\
CategoryC\
CategoryD\
Answer1\
Answer2\
Answer3\
Answer4

I'm trying to format the output for 1 to look like this

CategoryA - Answer1\
CategoryB - Answer2\
CategoryC - Answer3\
CategoryD - Answer4

However I am having trouble, I have also tried the following

sed -e '1~11{h;d};G'
column -t
awk '{ print $2 " " $1}'

I am not the best at formatting, as I'm newer to coding. I can pull data from querys, databases etc. Just gotta get better at formatting the output. I appreciate yall taking time out of your day to help with this!

Upvotes: 1

Views: 104

Answers (1)

RavinderSingh13
RavinderSingh13

Reputation: 133458

EDIT: Since OP changed the samples completely so adding solution as per new samples now.

awk '
BEGIN{ OFS=" - " }
match($0,/Category[^\\]*/){
  val=substr($0,RSTART,RLENGTH)
}
!/Category/{
  found=1
}
found && !/Category/{
  print arr[++count],$0
  next
}
{
  arr[FNR]=val
}
'  Input_file


Considering your Input_file looks same as shown samples strictly here, written and tested it in following link https://ideone.com/8XEVBW

awk '
BEGIN{ OFS=" - " }
match($0,/[^0-9]+/){
  val=substr($0,RSTART,RLENGTH)
}
prev!=val && prev{
  found=1
}
found{
  print arr[++count],$0
  next
}
{
  arr[FNR]=$0
  prev=val
}
'  Input_file

Output will be as follows with shown samples.

Example1 - Answer1
Example2 - Answer2
Example3 - Answer3
Example4 - Answer4

Upvotes: 3

Related Questions