PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, August 15, 2022

[FIXED] Why is my sed output to file different from terminal output?

 August 15, 2022     bash, output, sed     No comments   

Issue

Newbie here, so apologies for any missing info/silly mistakes!

I have a text file that contains a series of datasets. Each dataset comprises 6 sets of coordinates ('landmarks'), a scale and a specimen ID, like so;

LM=6
111 111
222 222
333 333
444 444
555 555
666 666
SCALE=0.123
ID=MS17_female_8_central_2.jpg

I wanted to move the first coordinate down to be the sixth coordinate, like so;

LM=6
222 222
333 333
444 444
555 555
666 666
111 111
SCALE=0.123
ID=MS17_female_8_central_2.jpg

So I tried using sed (probably clumsily). This works in the terminal;

sed '/LM/{n;H;d;}; /SCALE/{x;1!G;s/\n//;}' < in.txt

Everything looks good. However, as soon as I try this;

sed '/LM/{n;H;d;}; /SCALE/{x;1!G;s/\n//;}' < in.txt > out.txt

The output in the created file is different. The first chunk of data looks fine, but from then onward, I have also managed to insert the 'SCALE' line from the previous chunk...

LM=6
222 222
333 333
444 444
555 555
666 666
111 111
SCALE=0.123
ID=MS17_female_16_central2.jpg

LM=6
222 222
333 333
444 444
555 555
666 666
SCALE=0.123
111 111
SCALE=0.124
ID=MS17_female_18_central2.jpg

LM=6
222 222
333 333
444 444
555 555
666 666
SCALE=0.124
111 111
SCALE=0.125
ID=MS17_female_19_central2.jpg

I can well believe that I did something stupid in my sed, but I cannot work out why the terminal and file outputs would be different.. any help much appreciated!


Solution

This might work for you (GNU sed):

sed '/^LM/{n;h;d};/^SCALE/{x;p;x}' file

Match a line beginning LM then print it, fetch the next into the hold space and delete the fetched line.

Match a line beginnng SCALE, swap to the hold space, print it and swap back.

N.B. The h command overwrites what is already in the hold space whereas the H command appends to it (with a newline as a separator). Likewise the g command replaces the current line with the contents of the hold space and the G command appends the hold space to the current line (with a newline as a separator).


Applying a bit more thought:

sed '/^LM/{n;h;d};/^SCALE/{H;g}' file


Answered By - potong
Answer Checked By - Mary Flores (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing