The script below looks at printing any text after the first occurrence of pattern "Word1 word2" from file1.txt in another file called newfile.txt:

sed -n -e 's/^.*Word1 word2/\1/p' file1.txt > newfile.txt

When I input this in the Terminal, nothing happens (I don't get an error message either). Note that I am using UNIX on a Mac OS X.

1 Answer 1


The command

sed -n -e 's/^.*Word1 word2/\1/p' file1.txt

is not well defined, as the right hand side of the substitute command includes a backreference, but there is no capturing group on the left hand side. GNU sed 4.7 in linux gives an error message "invalid reference \1 on `s' command's RHS".

Since the requirement is to print the text after the first occurrence of "Word1 word2" we can't just use .*Word1 word2 as the .* is greedy. Instead we will use a trick and convert the first Word1 word2 into a single character and then delete up to that character. Any unused character will do, but a good choice is a newline as sed removes the newline as it reads each line and adds one when the line is printed. So we have

sed -n -e 's/Word1 word2/\n/;s/^.*\n//p' file1.txt > newfile.txt

If the "Word1 word2" was wanted then use

sed -n -e 's/Word1 word2/\n&/;s/^.*\n//p' file1.txt > newfile.txt

You must log in to answer this question.

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