3

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.

5

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
2
  • 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
5

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}
'
1
  • 1
    Compared to the other solutions, yours reduces the availability of human error and is significantly more readable. – Jodie C Mar 25 '12 at 4:52
1

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
0

This is basically a mix of the two previous awk answers

`awk -F@ -vOFS=@ -vq='"' '{print q$1q, $2, q$3q, $4}`
0

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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