sed question
I am learning to write bash scripts, and i created a little project for myself to give me practice in what i've already learned. I am trying to format a text file with sed in a script set to run everyday at a given time. the first 10 or so lines are fluff and can be deleted, so i use read to loop through each line until i find the text that signifies the end of lines to be deleted; also, as i loop through each line i increase a variable by one as shown below:
Code:
while read line; do Code:
cat /home/myname/Documents/Testfile.txt | sed '1,10d' Code:
cat /home/myname/Documents/Testfile.txt | sed '1,$id' |
You need to encapsulate your variable so the shell will understand where the variable name starts and stops. By having the d just after the name the shell is thinking the variable is $id instead of just $i.
Instead of "$id" use "${i}d". The brackets make it clear where the variable name starts and stops. |
single quotes take everything literally;
sed '1,$id' is not the same as sed "1,$id" Code:
id=10 |
As MensaWater pointed out though, "$i" is the variable, and "d" is the sed command for deletion. The string "$id" would be read as a single variable name and cause an error. So you need to make sure to use the full variable form to differentiate them.
( Or else just stick a space between them; sed won't mind. ) Also, useless use of cat. sed can take the file name as an argument. Code:
sed "1,${i}d" /home/myname/Documents/Testfile.txt |
Thank you all for the responses. I've caught this same mistake in other scripts I've conjured up, so I'm a little embarrassed I didn't catch it this time around...10th time is the charm maybe. anyway, for anybody who finds this post helpful, my final version of the the code i used to delete $i (number) of lines of a text file is:
Code:
while read line; do |
Read these three links for a better understanding of how the shell handles arguments and whitespace:
http://mywiki.wooledge.org/Arguments http://mywiki.wooledge.org/WordSplitting http://mywiki.wooledge.org/Quotes Based on this, you should really be quoting the entire expression, to ensure that the shell passes the whole thing to sed as a single unit: Code:
sed "1,${i}d" /home/myname/Documents/Testfile.txt By the way, it's possible to what you want entirely inside sed, too. Code:
sed '0,/some text/ {/some text/! d}' /home/myname/Documents/Testfile.txt Code:
0,/some text/ Code:
{...} Code:
/some text/! d Here are a few useful sed references. http://www.grymoire.com/Unix/Sed.html http://sed.sourceforge.net/sedfaq.html http://sed.sourceforge.net/sed1line.txt I've found the sed faq to be very useful for figuring out how to do things like this. |
All times are GMT -5. The time now is 06:54 AM. |