1

Using sed command I want to delete every other three lines from a file which has e.g. 99 lines in total. I mean to keep the first three lines and delete the second three lines and so on.

My starting script is as below:

for i in `seq 1 6 99`; do
   sed '$i,${i+2}!d' test.txt > o$i.txt
done
cat o*.txt > O.txt
rm o*.txt

Individual i works fine, likes

sed '1,3!d' test.txt > o1.txt
sed '7,9!d' test.txt > o7.txt
...

But it doesn't works inside sed. Would you please let me know where I am doing wrong? Thanks

Freddy
  • 25,565

1 Answers1

4

As hinted in the comment, you need proper quoting of your variables in your sed call:

for i in $(seq 1 6 99); do
    sed "$i"','"$((i+2))"'!d' test.txt > "o$i.txt"
done

Your variables are not expanded in singles quotes and taken literally ($i = insert before the last line). The expansion works with double quotes (no quotes also work in this example) and you need $((…)) for the arithmetic evaluation and to output its result. The remaining parts of the script remain in single quotes.

You should also use the newer $(…) syntax for the command substitution instead of the deprecated backticks `…` which makes quoting easier. Here is a good example.


But you can use GNU sed's first~step operator instead of a loop:

sed '4~6{N;N;d}' file

Example:

$ seq 20 | sed '4~6{N;N;d}'
1
2
3
7
8
9
13
14
15
19
20

Explanation:

sed '4~6d' would delete line 4 and then each 6th line 10, 16, 22 ...

With {N;N;d} two additional lines are deleted which are 4,5,6, then 10,11,12 ...

Freddy
  • 25,565