Insert Text from File Inline After Matching Pattern – Sed and Awk Tips

awksedtext processing

I'm trying to take the contents of a file and insert it after a matching pattern in another file using sed. My question is very similar to this question, but I wish to insert the contents of a file inline rather than on a new line. How can I do this?

Using the example question I referenced, the first answer does exactly what I want; however, I want the insertion to happen inline:

sed '/First/r file1.txt' infile.txt 

The actual data I want to insert is a JSON file:

[
    {
        "foo": "bar", 
        "baz": "biff",
        "data": [
            {
                "a": 1945619, 
                "b": [
                    {
                        "c": 512665, 
                        "d": "futz"
                    }
                ]
            }
        ]
    }
]

Best Answer

In your linked question there is already good awk answer, just modify it a little bit by using printf instead of print to insert the content without newline:

awk '/First/ { printf $0; getline < "File1.txt" }1' infile.txt

Result:

Some Text here
FirstThis is text to be inserted into the File.
Second
Some Text here

You may want to add space or other delimeter after "First" with printf $0 " "; ...


If inserted file has many lines then:

awk '/First/{printf $0; while(getline line<"File1.txt"){print line};next}1' infile.txt

Result:

Some Text here
First[
    {
        "foo": "bar", 
        "baz": "biff",
        "data": [
            {
                "a": 1945619, 
                "b": [
                    {
                        "c": 512665, 
                        "d": "futz"
                    }
                ]
            }
        ]
    }
]
Second
Some Text here
Related Question