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!

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 ...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.