Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does 'G' do with sed command?

Tags:

bash

sed

I have tried two different sed commands against a text file called "file1.txt". I have received the same result or output. What I don't understand is the meaning or use of "G" option! I have searched online, but I couldn't find a good answer!

Here are two commands:

sed 'G' file1.txt
sed '/^$/d;G' file.txt

Both commands give the same output! They create a one line gap between each line in the text file! I know that'^$' refers to line containing nothing, but what does 'G' do. For example if I put 'd' instead of 'G' all blank lines will be deleted!

like image 708
Scott Pearce Avatar asked Jun 18 '26 03:06

Scott Pearce


1 Answers

Get with g or G

Instead of exchanging the hold space with the pattern space, you can copy the hold space to the pattern space with the "g" command. This deletes the pattern space. If you want to append to the pattern space, use the "G" command. This adds a new line to the pattern space, and copies the hold space after the new line.

That is, instead of swapping the current contents of the hold and pattern space (current line, etc) you can take the pattern space and copy it into the hold space (either replacing or appending to the hold space in the process).

Those two sed commands are among the idiomatic sed one-liners that you can find online and they do the same thing only for certain files (those without blank lines in them).

 # double space a file
 sed G

 # double space a file which already has blank lines in it. Output file
 # should contain no more than one blank line between lines of text.
 sed '/^$/d;G'
like image 110
Etan Reisner Avatar answered Jun 20 '26 21:06

Etan Reisner



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!