Stefan Gehrig
Stefan Gehrig

Reputation: 25

replace line feeds with sed in a certain range of line

Is it possible to replace /n (e.g., with space) in a certain range of line position with sed?

Here is a sample without range filter. Is it somehow possible to set a range in sed?

for f in `find ${_filedir} -type f`
do
  #replace all LF with spaces
  sed 's/\n/ /g' ${f} > ${f}.noCR
done

Ok, here a sample:

Let's take some lines:

"I want to break free now"
"And friends will be friends"

I want to replace any "n" with an "m" in range 0 to 16, which results:

"I wamt to break free now"
"Amd friemds will be friends"

Upvotes: 1

Views: 497

Answers (1)

Mark Setchell
Mark Setchell

Reputation: 207415

Edited again

Try awk:

awk '{l=substr($0,1,10);r=substr($0,11);gsub(/n/,"m",l);print l r}' file

where l is the left part of the string and r is the right and gsub() does global substitutions.

Edited

I would probably use Bash parameter substitution for that - documentation here:

#!/bin/bash
while read line
do
   left=${line:1:16}    # Get left 16 chars
   right=${line:17}     # Get remainder of line
   left=${left//n/m}    # Do global replacement in left part
   echo $left $right    # Show output
done < file

Original answer

Sure, just on lines 2-8

sed '2,8s/foo/bar/' file

Or, between start and end patterns:

sed '/start/,/end/s/foo/bar/' file

Upvotes: 2

Related Questions