Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Double spacing file using sed in shell script

Tags:

shell

unix

sed

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
like image 877
jbisa Avatar asked Feb 19 '12 00:02

jbisa


People also ask

How do you put a space between lines in shell script?

The G command appends a newline and the hold space to the end of the pattern space. Since, by default, the hold space is empty, this has the effect of just adding an extra newline at the end of each line. The prefix $! tells sed to do this on all lines except the last one.

Can you use sed in a shell script?

Within a shell script, sed is usually one of several tool components in a pipe. Sed determines which lines of its input that it will operate on from the address range passed to it.

How do you sed multiple times?

You can tell sed to carry out multiple operations by just repeating -e (or -f if your script is in a file). sed -i -e 's/a/b/g' -e 's/b/d/g' file makes both changes in the single file named file , in-place.

Does sed overwrite file?

By default sed does not overwrite the original file; it writes to stdout (hence the result can be redirected using the shell operator > as you showed).


1 Answers

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}
like image 196
Dan Fego Avatar answered Sep 22 '22 06:09

Dan Fego