0
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
Jeff Schaller
  • 67,283
  • 35
  • 116
  • 255
Mark
  • 3

1 Answers1

0

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
Kusalananda
  • 333,661