2

What I want to do exactly is switch the first word of paired lines using sed. I know this could be easier using something else, but sed is required unfortunately (testing myself)

So, and example would be

One line here
Two line here as well
Third line could be here
fourth line to end

would end up being

Two line here
One line here as well
fourth line could be here
third line to end

I might have been using the wrong operation in sed but yeah, no idea. any clues?

Birei
  • 35,723
  • 2
  • 77
  • 82
spaztik
  • 21
  • 1

2 Answers2

3
sed -e 'N; s/\([a-zA-Z]*\)\(.*\)\n\([a-zA-Z]*\)\(.*\)/\3\2\   ⏎
\1\4/'

(yes, that is an explicit line break escaped by a backslash in the substitute)

Francois G
  • 11,957
  • 54
  • 59
  • +1 But why don't you write a literal `\n` in the replacement string, as `\3\2\n\1\4/`? It's easier to read for me. – Birei May 01 '12 at 18:11
  • Yes. In a linux shell the output is the same in both cases. – Birei May 01 '12 at 18:22
  • Which shell ? (ps -p $$) In bash/zsh/sh/csh, with those quotes, the \n escapes to the n letter. The escape I suggest is [somewhat](http://stackoverflow.com/questions/1421478/how-do-i-use-a-new-line-replacement-in-a-bsd-sed) [standard](http://docstore.mik.ua/orelly/unix/upt/ch34_08.htm) [advice](http://stackoverflow.com/questions/8991275/escaping-newlines-in-sed-replacement-string). – Francois G May 01 '12 at 18:41
  • From your last link I understand that is not a shell issue. Mine is `bash`, but the `\n` use in replacement wouldn't work in `BSD` and `Solaris`, regardless of the shell. – Birei May 01 '12 at 19:23
1

This might work for you (probably GNU sed):

sed '$!N;s/\(\S*\)\(.*\n\)\(\S*\)/\3\2\1/' file
Two line here
One line here as well
fourth line could be here
Third line to end
potong
  • 55,640
  • 6
  • 51
  • 83