1

I am trying to use sed in a script but it keeps failing. The commands on their own seem to work so I am not sure what I am doing wrong:

This is in Terminal in OS X (bash)

NOTE: file1.txt contains multiple lines of text

N=1
sed -n $Np < file1.txt > file2.txt
CONTENT=$(cat file2.txt)
echo $CONTENT

If I change $N to 1, it works perfectly

sed -n 1p <file1.txt >file2.txt
CONTENT=$(cat file2.txt)
echo $CONTENT

gives me

content of file2.txt

So basically, I am trying to copy the text from line 1 of a file to the start of line 2 of a file ... IF line 2 does not already start with the content of line 1.

ryankenner
  • 33
  • 3

4 Answers4

3

The shell doesn't know that you want $N and not $Np.

Do this: ${N}p

paddy
  • 60,864
  • 6
  • 61
  • 103
2

Change:

sed -n $Np < file1.txt > file2.txt

to

sed -n ${N}p < file1.txt > file2.txt

You code has no clue what variable Np is...

David C. Rankin
  • 81,885
  • 6
  • 58
  • 85
0

Since N was an integer, I ended up using the following.

sed -n `expr $N`p < file1 > file2

This also allows me to get the next line in a file using

sed -n `expr $N+1`p < file1 > file2

Thanks for your help!!!

ryankenner
  • 33
  • 3
  • This does not utilise any of the advice that was provided in the answers you were given. Using `expr $N` is overkill. If you want to get `N+1`, you can use Bash syntax: `$((N+1))`. – paddy Jul 13 '15 at 03:52
-1

You should use >> for append redirection. > overwrites the original file.

How to append the output to a file?

franciscod
  • 992
  • 4
  • 17