Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using sed between specific lines only

Tags:

regex

unix

sed

I have this sed command for removing the spaces after commas.

 sed -e 's/,\s\+/,/g' example.txt

How can i change it that, it will make the modification between only specific line numbers.

(e.g. between second and third lines).

like image 620
hackio Avatar asked Apr 24 '13 21:04

hackio


People also ask

How do you use sed on a specific line?

Just add the line number before: sed '<line number>s/<search pattern>/<replacement string>/ . Note I use . bak after the -i flag. This will perform the change in file itself but also will create a file.

Can sed match multiple lines?

By using N and D commands, sed can apply regular expressions on multiple lines (that is, multiple lines are stored in the pattern space, and the regular expression works on it): $ cat two-cities-dup2.

How do you edit a specific line in Unix?

To do this, press Esc , type the line number, and then press Shift-g . If you press Esc and then Shift-g without specifying a line number, it will take you to the last line in the file.


2 Answers

Use:

sed '2,3s/,\s\+/,/g' example.txt
like image 184
anubhava Avatar answered Oct 11 '22 09:10

anubhava


Since OSX (BSD sed) has some syntax differences to linux (GNU) sed, thought I'd add the following from some hard-won notes of mine:

OSX (BSD) SED find/replace within (address) block (start and end point patterns(/../) or line #s) in same file (via & via & via & section 4.20 here):

Syntax:

$ sed '/start_pattern/,/end_pattern/ [operations]' [target filename]

Standard find/replace examples:

$ sed -i '' '2,3 s/,\s\+/,/g' example.txt
$ sed -i '' '/DOCTYPE/,/body/ s/,\s\+/,/g' example.txt

Find/replace example with complex operator and grouping (cannot operate without grouping syntax due to stream use of standard input). All statements in grouping must be on separate lines, or separated w/ semi-colons:

Complex Operator Example (will delete entire line containing a match):

$ sed -i '' '2,3 {/pattern/d;}' example.txt

Multi-file find + sed:

$ find ./ -type f -name '*.html' | xargs sed -i '' '/<head>/,/<\/head>/ {/pattern/d; /pattern2/d;}'

Hope this helps someone!

like image 32
Astockwell Avatar answered Oct 11 '22 10:10

Astockwell