Mason
Mason

Reputation: 7103

Using sed to write a script to copy a number of lines from one file to another

I'm trying to write a script that takes two files and a number as its parameters and copies that number of lines from one file to the other. Here's what I have:

#!/bin/bash

file1=$1
file2=$2
lines=$3

sed -n '1,\'$lines\'p' $file1 > $file2

Obviously the problem is the formatting of the $lines parameter. What's the right way to do this? Thanks!

Upvotes: 0

Views: 4271

Answers (2)

dschultz
dschultz

Reputation: 485

sed -n -e "1,${lines}p" $file1 > $file2

alternately:

head -n $lines $file1 > $file2

Upvotes: 1

jaypal singh
jaypal singh

Reputation: 77185

You don't have to escape the single quotes. Do something like this -

#!/bin/bash

file1=$1
file2=$2
lines=$3

sed -n '1,'$lines'p' $file1 > $file2

OR

sed -n "1,"$lines"p" $file1 > $file2

Upvotes: 1

Related Questions