0

I've been trying to figure out how to copy lines from one file to the end of another using sed with some shell variables.

sed -n "$var1,$var2'p'" file1.txt > file2.txt

I've tried that and many close variations but no cigar. Could someone please enlighten me about the correct syntax? Thanks.

EDIT

So I tried to suggestions below but now I get this error

sed: -e expression #1, char 2: invalid usage of line address 0
sed: -e expression #1, char 2: unknown command: `*'"

EDIT

Ok these suggestions helped and I found another issue and now my script is running flawlessly. Thank you so much!

2
  • 1
    What error do you receive when running the sed command in your question? Please edit your post and provide that information.
    – Peschke
    Aug 27, 2019 at 0:06
  • 1
    > file2.txt will overwrite file2: if you want to append the copied lines to the end of the file, use >> file2.txt Aug 27, 2019 at 0:07

2 Answers 2

2

Freddy's answer works, but lacks an explanation. The sed format that you are probably aiming for is something like

sed -n 4,6p file1.txt

Where I've used 4 and 6 as dummy numbers.

Let's examine your expression, using these dummy numbers again, and the echo command.

$ var1=4
$ var2=6
$ echo "$var1,$var2'p'"
4,6'p'

Because you enclosed the 's in the "s, they are interpreted literally, and you are literal 's to the sed command. Hence, when you try to run your command:

$ sed -n "$var1,$var2'p'" file1.txt
sed: -e expression #1, char 4: unknown command: `''

Solution

You can remove the 's from your expression, but this would change the variable name to $var2p instead. Hence, as Freddy suggests, you can use {…} to explicitly enclose the variable name(s). i.e.

sed -n "${var1},${var2}p" file1.txt

You can test if this works by putting an echo before the command. An alternative format is

sed -n "$var1,$var2"p file1.txt

but IMO it's less readable.

Finally, as steeldriver points out, if you are aiming to append to the file, use >> file2.txt instead of > file2.txt.

1

Use curly braces around your variable names:

sed -n "${var1},${var2}p" file1.txt > file2.txt

The braces around the first variable are not needed, but better make it consistent.

0

You must log in to answer this question.

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