Using sed between specific lines only Using sed between specific lines only unix unix

Using sed between specific lines only


Use:

sed '2,3s/,\s\+/,/g' example.txt


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!


sed -e '2,3!b;s/,\s\+/,/g' example.txt

This version can be useful if you later want to add more commands to process the desired lines.