0

all experts

I have two types of files in the same directory

ex1) record1.txt (record2, record3, record4 ...)

11111 absda qwedc
11112 uiyds dqeds
11113 eqwev jfsec ...

ex2) Summary1.txt (Summary2, Summary3, Summary4 ...)

----some data is written---- 
.....
.....
***RESULT 111.114 30.344 90.3454***  OTHERNUMBER#1 OTHERNUMBER#2 ..... 
.....
.....

All I want to do is extract RESULT X(number) Y(number) Z(number) of Summary#.txt. And then, put those positions into the corresponding record#.txt, but I want to add some information, like this

X Y Z
111.114 30.344 90.3459

11111 absda qwedc
11112 uiyds dqeds
11113 eqwev jfsec ...

So, I want my final file, record#.txt, to look above. I tried sed and cat... all failed.

Thanks in advance!

1
  • Did you tried awk? Commented Aug 21, 2019 at 20:56

2 Answers 2

0

If I undersand you correctly, this is my proposal:

for i in record*.txt; do
  xyz=$(grep -oP "(?<=RESULT ).*(?=\*\*\*)" $i)
  sed -i "1 iX Y Z\n$xyz\n" summary${i//record/}
done

Loop through the files named record*.txt

for i in record*.txt; do

Capture the string between RESULT and ***

xyz=$(grep -oP "(?<=RESULT ).*(?=\*\*\*)" $i)

Add X Y Z in the first line, following by the captured pattern, in the file summary*.txt

sed -i "1 iX Y Z\n$xyz\n" summary${i//record/}
0

This is just a simple concatenation of a line with fixed text (X Y Z) and part of a single line from one file (SummaryX.txt) and the entire contents of another file with a related filename (recordX.txt)

#!/bin/sh

for sfile in Summary*.txt; do
  rfile="$(echo "$sfile" | sed -e 's/^Summary/record/')"
  ofile="$rfile.new"

  {
    echo X Y Z

    sed -E -n -e 's/^.*RESULT ([0-9.]+ [0-9.]+ [0-9.]+).*/\1/p' "$sfile"
    echo

    cat "$rfile"
  } > "$ofile"

  # uncomment the following to replace the original record file with the new one.
  # mv -f "$ofile" "$rfile"
done

You haven't said which shell you're using, so this doesn't use any bash-specific string manipulations or other features. It should work with any sh-compatible shell.

The output will be stored in recordX.txt.new unless you uncomment the mv line. This is so that you can verify that it does what you want before it destroys your original input files (you should be working on backup copies anyway when doing something potentially destructive).

$ cat record1.txt.new 
X Y Z
111.114 30.344 90.3454

11111 absda qwedc
11112 uiyds dqeds
11113 eqwev jfsec ...
2
  • Thank you very very much!
    – newkis
    Commented Aug 26, 2019 at 16:06
  • no problem. btw, upvoting and/or accepting an answer (by clicking on the tick mark to the left) is how we say thanks on stack exchange sites
    – cas
    Commented Aug 27, 2019 at 0:31

You must log in to answer this question.

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