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
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.
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.
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.
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).
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}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With