LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - General (https://www.linuxquestions.org/questions/linux-general-1/)
-   -   Having some trouble with sed (https://www.linuxquestions.org/questions/linux-general-1/having-some-trouble-with-sed-396924/)

P0ldy 12-27-2005 01:54 PM

Having some trouble with sed
 
OK, so here's what I'm trying to do. I've got a file with, for example, the following lines:

Code:

First_Name: John
Last_Name: Smith
Address: 123 Anywhere
Phone: 555-5555
 
First_Name: Jane
Last_Name: Jones
Address: 321 Anywhere
Phone:111-1111

I'm trying to use sed to place each line from First_Name: to Phone: on a single line delimited by tabs, and then the next "First_Name" block on its own line with the same tab delimited fields. However, I just can't seem to figure out the right expression. If I use

sed 's/First_Name*\n/\t/g' foo > bar

nothing happens. Just using sed 's/\n/\t/g' gives me nothing, as if there are no newline characters in this text file at all, when there clearly are.

Anyone have any ideas? I've also tried to outright delete newline characters with sed '/\n/d' and nothing happens. If I use sed '/$/d', however, it erases the contents of the entire file, when I'm only interested in deleting the final end-of-line character, the newline.

Can anyone help?

homey 12-27-2005 04:08 PM

Here's an example using awk. I'll give sed a try later.
Code:

awk 'BEGIN { FS="\n" ; RS="\n\n" ; OFS="\t" } {print$1,$2,$3,$4}' file.txt

jschiwal 12-27-2005 04:57 PM

You may want to use the "tr" program to replace the new-lines with tabs. This would be an easier solution than using Sed. Using sed, because it's a line editor, you would have to build up the fields in the HOLD buffer before you could perform the substitution.

P0ldy 01-04-2006 04:07 AM

Thanks for the replies.

I did use tr in the end. Awk's a bit too intimidating for me. ;)

Tinkster 01-04-2006 11:27 AM

I'm curious ... how did you stop tr from putting ALL lines into one line?


Cheers,
Tink

P0ldy 01-04-2006 02:26 PM

I figured that would be a problem. So, after switching out the \n for \t, I used sed -e 's/First_Name/\nFirst_Name/g', because I wanted each newline to begin with First_Name.

pixellany 01-04-2006 04:26 PM

Quote:

Originally Posted by P0ldy
Thanks for the replies.

I did use tr in the end. Awk's a bit too intimidating for me. ;)

Hmmmm: If awk is intimidating, then sed is your worst nightmare.....
To really write test manipulation scripts, you need both.

In fairness, I went thru a "sed" phase, where I struggled mightly to make it do everything. Then I bit the bullet and learned awk. Now I know enough about both of them to look up the exact syntax when I need to do something.


All times are GMT -5. The time now is 05:56 PM.