jbisa
jbisa

Reputation: 141

Double spacing file using sed in shell script

I am new to shell scripting and I used the following code to double space a file (input file is a parameter):

sed G $input_file >> $input_file

The problem is, if the content of my original file is:

Hi
My name is

My double-spaced file is:

Hi
My name is
Hi

My name is

Is there something else I need to add in the shell script so that my file will only be:

Hi

My name is

Upvotes: 5

Views: 1761

Answers (1)

Dan Fego
Dan Fego

Reputation: 14004

You're using the append operator (>>), which appends to the file in question. That being said, you can't generally operate on and output to the same file with > in bash, either. For sed's specific case, you can use the -i option (depending on version and platform):

sed -i G $input_file

That should edit your file "in place", if your version has that option. I say "in place" because I'm pretty sure it actually creates a new file and moves it back on top of the first one for you (inode is different). If not, you'd output to a separate file, and move the file back:

sed G ${input_file} > ${input_file}.bak
mv ${input_file}.bak ${input_file}

Upvotes: 5

Related Questions