Home > Enterprise >  How to use locale variable and 'delete last line' in sed
How to use locale variable and 'delete last line' in sed

Time:10-18

I am trying to delete the last three lines of a file in a shell bash script.

The commands I have available is limited, since I am not on a Linux but use a MINGW64 for it. sed does a create job so far, but deleting the last three lines gives me some headaches in relation of how to format the expression.

I use wc to be aware of how many lines the file has and subtract then with expr three lines.

n=$(wc -l < "$distribution_area")
rel=$(expr $n - 3)

The start point for deleting lines is defined by rel but accessing the local variable happens through the $ and unfortunately the syntax of sed is using the $ to define the end of file. Hence,

sed -i "$rel,$d" "$distribution_area"

won't work, and what ever variant of combinations e.g. '"'"$rel"'",$d' gives me sed: -e expression #1, char 1: unknown command: `"' or something similar.

Can somebody show me how to combine the variable with the $d regex syntax of sed?

CodePudding user response:

sed -i "$rel,$d" "$distribution_area"

Here you're missing the variable name (n) for the second arg.

Consider the following example on a file called test that contains 1-10:

n=$(wc -l < test)
rel=$(($n - 3))

sed "$rel,$n d" test

Result:

1
2
3
4
5
6

To make sure the d will not interfere with the $n, you can add a space instead of escaping.


If you have a recent head available, I'd recommend something like:

head -n -3 test

CodePudding user response:

Can somebody show me how to combine the variable with the $d regex syntax of sed?

$d expands to a varibale d, you have to escape it.

"$rel,\$d"

or:

"$rel"',$d'

But I would use:

head -n -3 "$distribution_area" > "$distribution_area".tmp
mv "$distribution_area".tmp "$distribution_area"
  • Related