8

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!

0

2 Answers 2

6

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'
5

According to the man sed:

  • g

    Replace the contents of the pattern space with the contents of the hold space.

  • G

    Append a newline to the contents of the pattern space, and then append the contents of the hold space to that of the pattern space.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.