Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

I have a file like this:

78@54@this@15@23
65@22@is@92@16
34@12@an@14@18
13@42@example@52@22

And I want to change it to this:

"78"@54@"this"@15@23
"65"@22@"is"@92@16
"34"@12@"an"@14@18
"13"@42@"example"@52@22

I've been struggling on this for a long time and I can't understand how to do it. Any help is appreciated, thank you.

share|improve this question
add comment

5 Answers

up vote 5 down vote accepted

You could try awk:

echo "78@54@this@15@23
65@22@is@92@16
34@12@an@14@18
13@42@example@52@22" |
awk -F@ '{print "\""$1"\"@"$2"@\""$3"\"@"$4"@"$5}' 

"78"@54@"this"@15@23
"65"@22@"is"@92@16
"34"@12@"an"@14@18
"13"@42@"example"@52@22
share|improve this answer
    
Ahh, what a simple solution, thank you. Why didn't I think of that? :-) –  user17000 Mar 25 '12 at 3:26
1  
Just by the way: You don't need a line-continuation backslash '\' after the pipe | ... Actually, you can have whitespace and/or a comment after the |. You can even have multiple lines of comments between the | and the command. –  Peter.O Mar 25 '12 at 14:33
add comment

A little more verbose, but I'd write this awk:

awk -F@ -v OFS=@ '
    function quote(x) {return sprintf("\"%s\"", x)}
    {print quote($1), $2, quote($3), $4}
'
share|improve this answer
1  
Compared to the other solutions, yours reduces the availability of human error and is significantly more readable. –  JodieC Mar 25 '12 at 4:52
add comment

I think an awk solution is probably better, but you can also use sed:

sed -r 's/(\d+)@(\d+)@(\w+)(.*)/"\1"@\2@"\3"\4/' /path/to/your/file
share|improve this answer
add comment

This is basically a mix of the two previous awk answers

`awk -F@ -vOFS=@ -vq='"' '{print q$1q, $2, q$3q, $4}`
share|improve this answer
add comment

In awk: add quotes around the first three fields, then print the line.

awk -F @ '{for (i = 1; i <= 3; i++) $i = "\"" $i "\""; print}'

-F @ sets the field separator to @. The loop adds quotes around the first three fields. The final print (short for print $0) prints the line with the modified fields; $0 is rebuilt whenever individual fields ($1, $2, …) are changed.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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