-1

I have a file with the following

firsttext=cat secondtext=dog thirdtext=mouse

and I want it to return this string:

"firsttext=cat" "secondtext=dog" "thirdtext=mouse"

I yave tried this one-liner but it gives me an error.

cat oneline | perl -ne 'print \"$_ \" '

Can't find string terminator '"' anywhere before EOF at -e line 1.

I don't understand the error.Why can't it just add the quotation marks?



Also, if I have a variable in this string, I want it to be interpolated like:

firsttext=${animal} secondtext=${othervar} thirdtext=mouse

Which should output

"firsttext=cat" "secondtext=dog" "thirdtext=mouse"
Borodin
  • 126,100
  • 9
  • 70
  • 144
alig227
  • 327
  • 1
  • 6
  • 17
  • Where are the values of the variables defined? – reinierpost Jun 26 '17 at 16:29
  • 1
    Your ***also*** is a whole other topic and you need to write a new question. You must think about where `$animal` and `$othervar` could be defined if you want to stick to a one-liner. Why does this all have to be in a single line of Perl anyway? – Borodin Jun 26 '17 at 17:41

2 Answers2

0
perl -lne '@f = map qq/"$_"/, split; print "@f";' oneline
Borodin
  • 126,100
  • 9
  • 70
  • 144
-2

What you want is this:

cat oneline | perl -ne 'print join " ", map { qq["$_"] } split'

The -ne option only splits on lines, it won't split on arbitrary whitespace without other options set.

tadman
  • 208,517
  • 23
  • 234
  • 262
  • @reinierpost That adds a newline at the end if that's desirable. – tadman Jun 26 '17 at 16:31
  • And removes it from the input. Without it, a word at the end of the line will go wrong. – reinierpost Jun 26 '17 at 16:33
  • @reinierpost The only effect it has is adding a newline on the end of the output. The last entry is unaffected. I tested by adding a blank line at the end of the file and it just carries through, it doesn't glom on to the third entry. – tadman Jun 26 '17 at 16:37
  • My apologies, you're right. But I don't think the OP wants all output on one line. – reinierpost Jun 26 '17 at 16:49
  • @reinierpost The `-l` flag is helpful though. Also just matching what's in the question as closely as possible. – tadman Jun 26 '17 at 16:57
  • @SinanÜnür It's in the original question. I'm making as few modifications as practical to get it working. This could be taking output from some other source, where `cat` is just a toy substitute. – tadman Jun 26 '17 at 17:19
  • @tadman: The `-l` option (without a value) sets `$\\` to `$/` so that `print` statements are terminated by a newline, and also does an implicit `chomp` on input lines, to remove the line terminator on input. The latter has no effect when `split ' '` is used, as it counts the newline as just more whitespace separation. – Borodin Jun 26 '17 at 17:25