LINEnum=$(grep -nr "#32" IM_DlCtrlRef.txt | cut -d : -f 1)
for j in $LINEnum
do
echo $j
sed -n '$j,4800p' IM_DlCtrlRef.txt >> IM_DlCtrlRef_bak
for insertl in {1..4}
do
cat zero.txt >> IM_DlCtrlRef_bak
done
done

- 67,283
- 35
- 116
- 255

- 3
1 Answers
Your main problem (the one that causes a syntax error) lies on the sed
line:
sed -n '$j,4800p' IM_DlCtrlRef.txt >> IM_DlCtrlRef_bak
You want to use the shell variable $j
in you sed
script as the start line number (the sed
script extracts lines $j
to 4800 out of a file), but you prevent the shell from expanding the variable by using single-quotes. This means that sed
will get $j
as the start address, which will confuse it no ends.
Simply change that line to have double-quotes instead.
Now, looking at the complete script:
LINEnum=$(grep -nr "#32" IM_DlCtrlRef.txt | cut -d : -f 1)
for j in $LINEnum
do
echo $j
sed -n "$j,4800p" IM_DlCtrlRef.txt >> IM_DlCtrlRef_bak
for insertl in {1..4}
do
cat zero.txt >> IM_DlCtrlRef_bak
done
done
This has a few style issues and performance issues that you may or may not want to fix.
Firstly, you read in all line numbers into a variable. This is a waste of memory, but you need to do this because the for
-loop needs to know exactly what to loop over.
Another solution would be to read the line numbers one by one:
grep -nr "#32" IM_DlCtrlRef.txt | cut -d : -f 1 |
while read j; do
# ...
done
This means there's no limit to how much data the script is able to gulp in.
BTW, -r
makes grep
search recursively, so that's probably not needed here. Replace it with -F
since you're looking for a fixed string (not a regular expression).
However, since you're only interested in line numbers of lines matching #32
, you could replace that whole pipe with
sed -n '/#32/=' IM_DlCtrlRef.txt
The sed
command =
prints line numbers.
With a final round of touch-up, the script becomes
sed -n '/#32/=' IM_DlCtrlRef.txt |
while read j; do
echo $j
sed -n "$j,4800p" IM_DlCtrlRef.txt >>IM_DlCtrlRef_bak
for insertl in {1..4}; do
cat zero.txt >>IM_DlCtrlRef_bak
done
done

- 333,661
-
@Mark, if you click to accept the answer the question is "formally" accepted. (and I get a bit of cred) – Kusalananda Jun 24 '16 at 07:10
-
first time use this , I not find where/how I to click the accept button. I will try it later, and thanks much. – Mark Jun 27 '16 at 07:46
-
@Mark under the up-vote/down-vote arrows to the left of the answer :-) – Kusalananda Jun 27 '16 at 07:47
"$j,4800p"
– Sundeep Jun 23 '16 at 08:34sed -n '/#32/,4800p' IM_DlCtrlRef.txt >> IM_DlCtrlRef_bak
– cas Jun 24 '16 at 04:24