2

I have two files. One, called file.gpx, is a list of trackpoints, each of which consists of three lines:

<trkpt...>
<ele>...</ele>
</trkpt>

The other, called times.txt, is a list of separate lines, each of which looks like this:

<time>...</time>

What I need to do is insert each <time>...</time> line from times.txt into file.gpx so that all trackpoints in file.gpx look like this:

<trkpt...>
<ele>...</ele>
<time>...</time>
</trkpt>

I was wondering how to achieve this.

(The ... represent different values, irrelevant for the purpose of my question.)

Thank you very much for your help.

0

3 Answers 3

4

Using awk:

awk '
  FNR==NR{             # if this is the first input file...
    t[++idx]=$0        # save record in array `t` at index `idx` (pre-incremented)
    next               # continue with next record
  }
  1                    # print record of second input file
  /<ele>.*<\/ele>/{    # if record matches...
    print t[++idx2]    # print array value at `idx2` (pre-incremented) 
  }
' times.txt file.gpx > new.gpx
2
  • Thank you very much, @Freddy. Sorry for the ignorant question, but do I copy and paste your answer straight as a command or do I need to put it into a script? Feb 9, 2021 at 21:03
  • You can put it into a script, but you can also paste it into your terminal.
    – Freddy
    Feb 9, 2021 at 21:05
3

With GNU sed, you can read and insert one line per match from a file using the R command:

sed '\:<ele>.*</ele>:R times.txt' file.gpx

You can redirect the result to a new file, or make the changes to file.gpx in-place by adding the -i option.

1

Using awk:

awk ' 
  BEGIN { f=ARGV[2]; ARGV[2]=""; }

  /<trkpt.*>/ {k=3}

  (k-->0) && (!k) &&
  (getline t < f > 0) {
     print t
  };1

  END { close(f) }
' file.gpx times.txt

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .