0

I have a file like this:

20180127200000
DEFAULT, Proc_m0_s1 
DEFAULT, Proc_m0_s2
DEFAULT, Proc_m0_s3
20180127200001
DEFAULT, Proc_m0_s1 
DEFAULT, Proc_m0_s2
DEFAULT, Proc_m0_s3

I'd like to convert to:

20180127200000 DEFAULT, Proc_m0_s1 
20180127200000 DEFAULT, Proc_m0_s2
20180127200000 DEFAULT, Proc_m0_s3
20180127200001 DEFAULT, Proc_m0_s1 
20180127200001 DEFAULT, Proc_m0_s2
20180127200001 DEFAULT, Proc_m0_s3

The time stamp appears every 4 lines.

tripleee
  • 175,061
  • 34
  • 275
  • 318
alfigue
  • 19
  • 1
  • 5
  • Not quite sure your question is really clear here. You have a data set but nothing of what you've done or are really trying to do. If you're trying to get the values from one line into a row you should split the one line up in a loop. This looks like it is comma separated so just loop, split on the comma and move it into an array. Then parse out the array. – Dylan Wright Jan 30 '18 at 14:04
  • Take a moment to read through the [editing help](//stackoverflow.com/editing-help) in the help center. Formatting on Stack Overflow is different than other sites. The better your post looks, the easier it is for others to read and understand it. – Blue Jan 30 '18 at 14:09

2 Answers2

1

Awk should be both faster and simpler than a shell loop for this type of task.

awk 'NR%4==1 { time=$1; next }
    { print time " " $0 }' file

NR is the line number. If the line number modulo 4 is one, remember the first field but don't print. Otherwise, print with the remembered value and a space as the prefix.

tripleee
  • 175,061
  • 34
  • 275
  • 318
0
iconvert() {
    while true; do
        read linePrefix || return 0
        for i in $(seq $((prefix_lines - 1))); do
            read line || return 0
            echo "$linePrefix" "$line"
        done
    done
}

You just call iconvert like this:

prefix_lines=4
iconvert < file.txt

which gives your desired output.

iBug
  • 35,554
  • 7
  • 89
  • 134
  • You probably want to avoid the horrible overhead of a `while read -r` loop (and even more a `while true; read` without `-r`). This should be basically a one-liner with Awk. – tripleee Jan 30 '18 at 14:10
  • @tripleee Not sure about that. What exactly is it? – iBug Jan 30 '18 at 14:11
  • See e.g. https://stackoverflow.com/questions/13762625/bash-while-read-line-extremely-slow-compared-to-cat-why – tripleee Jan 30 '18 at 14:12
  • @tripleee Problem is, I don't know `awk` :( – iBug Jan 30 '18 at 14:14