问题
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.
回答1:
The shell doesn't know that you want $N and not $Np.
Do this: ${N}p
回答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...
回答3:
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!!!
回答4:
You should use >> for append redirection. > overwrites the original file.
How to append the output to a file?
来源:https://stackoverflow.com/questions/31374269/using-sed-n-with-variables-in-a-script