0

I have shell script variable var="7,8,9" These are the line number use to delete to file using sed.

Here I tried: sed -i "$var"'d' test_file.txt

But i got error `sed: -e expression #1, char 4: unknown command: ,'

Is there any other way to remove the line?

2
  • Did you just write your variable like that because you thought it'd be useful, or is it the output of another command? It may be more convenient to have the list of numbers in a different format. Commented May 26, 2017 at 11:02
  • 1
    No i am just write my way. So you can use your way Commented May 26, 2017 at 12:26

4 Answers 4

1

sed command doesn't accept comma delimited line numbers.

You can use this awk command that uses a bit if BASH string manipulation to form a regex with the given comma separated line numbers:

awk -v var="^(${var//,/|})$" 'NR !~ var' test_file.txt

This will set awk variable var as this regex:

^(7|8|9)$

And then condition NR !~ var ensures that we print only those lines that don't match above regex.

For inline editing, if you gnu-awk with version > 4.0 then use:

awk -i inplace -v var="^(${var//,/|})$" 'NR !~ var' test_file.txt

Or for older awk use:

awk -v var="^(${var//,/|})$" 'NR !~ var' test_file.txt > $$.tmp && mv $$.tmp test_file.txt
Sign up to request clarification or add additional context in comments.

1 Comment

That will delete specific line numbers only due to use of anchors around the ( and )
0

I like sed, you were close to it. You just need to split each line number into a separate command. How about this:

sed -e "$(echo 1,3,4 | tr ',' '\n' | while read N; do printf '%dd;' $N; done)"

Comments

0

do like this:

sed -i "`echo $var|sed 's/,/d;/g'`d;" file

Comments

0

Another option to consider would be ed, with printf '%s\n' to put commands onto separate lines:

lines=( 9 8 7 )
printf '%s\n' "${lines[@]/%/d}" w | ed -s file

The array lines contains the line numbers to be deleted; it's important to put these in descending order! The expansion ${lines[@]/%/d} adds a d (delete) command to each line number and w writes to the file at the end. You can change this to ,p instead, to check the output before overwriting your file.

As an aside, for this example, you could also just use 7,9 as a single entry in the array.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.