2

I have a fileA and a fileB. In fileA, I want my script to find for a specific stringA; then, with sed command paste only a part of stringA on a file B (replacing with part of a specific stringB in fileB).

Eg.

fileA
ashdjkahsjd
asjkdhajsdh
Recommended Weight: 0.546 (this is the string of interest)

fileB
asdajskdha
kjashdjahsd
WGHT      0.495 (this is the part of FILE B I need to replace)

I want to select only the text of stringA (0.546) and replace 0.495 on fileB with 0.546, so, new fileB will be:

NEW fileB
asdajskdha
kjashdjahsd
WGHT      0.546

Using only sed doesn't work for me because it replaces a stringA with a stringB in the same file, but my stringsA and B are from different files. Also, they are generated "randomly" (via a program).

  • 1
    Please use the formatting tools to format the contents of your file as code. This is very hard to read. – terdon Aug 11 '17 at 17:56
5

You can actually do it with sed (and another tool to match the first file). For instance:

$ sed -E "s/(WGHT\s*).*/\1$(grep -oP 'Recommended Weight: \K[0-9.]+' fileA)/" fileB 
asdajskdha
kjashdjahsd
WGHT 0.546

Or just save it in a variable first:

$ wght=$(sed -En 's/Recommended Weight: *([0-9.]+)/\1/p' fileA)
$ sed -E "s/(WGHT\s*).*/\1$wght/" fileB
asdajskdha
kjashdjahsd
WGHT 0.546 
4
awk 'FNR==NR && $2 == "Weight:"{ weights[spotted++]=$3} FNR!=NR && $1 != "WGHT" { print } FNR!=NR && $1=="WGHT" { print "WGHT", weights[replaced++]} ' in1 in2 > out2

This will create a new file, out2, that has your desired output data. It can then be moved wherever you like.

$ cat out2
asdajskdha
kjashdjahsd
WGHT 0.546
3

This script create new_file_b.txt.

Usage: ./script.sh file_a.txt file_b.txt > new_file_b.txt

#!/bin/bash

awk '
/Recommended Weight: /{
    value=$3;
}
NR != FNR {
    if($1 == "WGHT") {
        print $1 OFS value; 
    } else {
        print;
    }
}
' "$1" "$2"
0

With GNU sed you can do it as follows:

sed -Ez '
   N;s/.*\nRecommended Weight: (\S+)\n.*\x00(.*\nWGHT[[:blank:]]+)\S+\n/\2\1\n/
' fileA fileB

Where the -E option turns on the extended regex facility and -z option treats each file as a single string and multiple files are null(\0) separated.

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.