1

This assistance was helpful, but I am still a bit lost. I'll steal it's super easy format. How to insert the content of a file into another file before a pattern (marker)?

I have two files.

File 1

test
test2
test3
test4

File 2

Numebr of results: 0
Numebr of results: 1

Object Name: 
Object UID: {A42CD268-ommitted}
Class Name: referral
    last_element: false
    referral_info: source 
    referral_obj: Name: ommitted (Table: ommitted)
    scheme_flags: 0
    type: member
Numebr of results: 0
Numebr of results: 0

Desired end result (file 3?)

test
Numebr of results: 0
test2
Numebr of results: 1

Object Name: 
Object UID: {A42CD268-ommitted}
Class Name: referral
    last_element: false
    referral_info: source 
    referral_obj: Name: ommitted (Table: ommitted)
    scheme_flags: 0
    type: member
test3
Numebr of results: 0
test4
Numebr of results: 0

Looking to read in one line at a time from file1, find the next pattern for "Numebr of results", insert line1 from file1 above the first match and successively iterate through the entire file as such.

Thank you so much in advance!!

2

I'd suggest using the Getline/Variable/File form of awk getline

$ awk '/^Numebr of results/ {if (getline line < "file1" > 0) print line} 1' file2
test
Numebr of results: 0
test2
Numebr of results: 1

Object Name:
Object UID: {A42CD268-ommitted}
Class Name: referral
last_element: false
referral_info: source
referral_obj: Name: ommitted (Table: ommitted)
scheme_flags: 0
type: member
test3
Numebr of results: 0
test4
Numebr of results: 0
1
$ awk 'NR==FNR{A[NR]=$0;next}{if($0~/^Numebr of results/){i++;print A[i]}}1' file1 file2
test
Numebr of results: 0
test2
Numebr of results: 1

Object Name:
Object UID: {A42CD268-ommitted}
Class Name: referral
    last_element: false
    referral_info: source
    referral_obj: Name: ommitted (Table: ommitted)
    scheme_flags: 0
    type: member
test3
Numebr of results: 0
test4
Numebr of results: 0
1

Could be done with sed, although awk would be more suitable:

echo "----" | cat file1 - file2 | sed -n '1,/----/{H;d}; /Numebr/ {x;s/^\n//;P;s/[^\n]*\n//;x;}; p'

0

I used subshell for manage file descriptor simple. ( no need to "exec 3>&-" )
file descriptor inherited to child process
If you used file descriptor like this then file position moved below by every read operations.
"e" option execute patteren space string as a command in sh

sh$ ( exec 3< file2; 

  sed -r '
    /^Number of results: [0-9]+/ {
    h
    s#.*#read line <\&3; echo -n "$line"#e
    G
    }
  ' file1; 
)
  • Could you please add a bit of explanation? – phk Jan 22 '17 at 16:41

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.