Replace the first character of the current line with the first character of the previous line. For example Input file:
Mark was
Great friend
And
Output file:
Mark was
Mreat friend
Gnd
Must be done with sed
I do not understand how to make the letter replace exactly the beginning of the word on the previous line, all I could do was add a character to the end of the line, but not to the beginning:
sed '2,$ s/[^.]/& &/; 2,$ s/ /\n/' file.txt | paste -d ' ' - -
Output:
Mark was G
Great friend A
And
I don't understand how exactly to specify in the regular expression to work at the beginning of the previous line.
CodePudding user response:
sed
is certainly the wrong tool for this! But this seems to do what you want:
sed -e 1's/./&&/' -e H -e 's/\(.\).*/\1/' -e x -e 's/\n.//' input
On the first line, you duplicate the first character to prime the hold space. For all lines, you append the line to the hold space (for this first line, this is the modified line with the first character duplicated). Then you remove all but the first char and swap the pattern space with the hold space. Then you remove the newline and the first character of the line, leaving the first character of the previous line and the remainder of the line in the pattern space, while only the first character is in the hold space. Print the pattern space and repeat.
CodePudding user response:
With your shown samples please try following awk
code. Simple explanation would be, if line number is more than 1 then print prev(which has first character of previous line) as first character and then print rest of line. And set each line's first character to prev variable to become first for its next line.
awk '
FNR==1{ print }
FNR>1 {
print prev substr($0,2)
}
{
prev=substr($0,1,1)
}
' Input_file
OR more precisely:
awk '
FNR>1 {
$0 = prev substr($0,2)
}
{
prev=substr($0,1,1)
}
1
' Input_file