How to to Delete a Line Given with a Variable in Sed

How to delete a line by passing line number as variable?

For a given file like

$ cat file
1
2
3
4
5
6
7
8
9
10

and your variable containing the line number like

$ ERR=5

Using sed:

Use double quote to allow the variable to interpolate. Notice the use of curly braces to allow sed to differentiate between variable and d flag. In the output line number 5 is no longer printer.

$ sed "${ERR}d" file
1
2
3
4
6
7
8
9
10

Using awk:

NR stores the line number for a given file. Passing the shell variable to awk using -v option we create an awk variable called no. Using the condition where NR is not equal to our awk variable we tell awk to print everything except the line number we don't want to print.

$ awk -v no="$ERR" 'NR!=no' file
1
2
3
4
6
7
8
9
10

Using a variable in sed to delete a line number by choice of user

Variables aren't expanded inside single quotes. You should just use double quotes. Use curly braces to delimit the variable from the d command.

sed -i "${lineNum}d" speciesDetails.txt

Bash: Delete a line from a file matching a variable

As you have already understood, variables inside '...' are not expanded.

If you replace the single-quotes with double-quotes,
this will delete the matching line from ./wrong:

sed -i "/$x/d" ./wrong

But you also want to add the line to ./correct, if there was a match.
To do that, you can run grep before the sed:

grep "$x" ./wrong >> ./correct

This will have the desired effect,
but sed will overwrite ./wrong, even when it doesn't need to.
You can prevent that like this:

if grep "$x" ./wrong >> ./correct; then
sed -i "/$x/d" ./wrong
fi

How to remove all lines in a file containing a variable, only when located on a line somewhere between braces in BASH?

sed -i "/{.*$word.*}/d" ./file.txt

\{ in sed actually have a special meaning, not the literal {, you should just write a { to represent the literal character. (which would be confusing if you are well familiar with perl regex ...)

Edit:

Be careful with -i, if this is in a script, and accidently $word is not defined or set to empty string, this command will delete all lines containing { no matter what between }.



Related Topics



Leave a reply



Submit