-1

I have in 1.txt:

https://www.google.se/
https://www.bing.com/
URL=$(grep ".*" ./1.txt) | sed "s/$/\">${URL}/" ./1.txt > ./2.txt

I get in 2.txt:

https://www.google.se/">
https://www.bing.com/">

I want in 2.txt:

https://www.google.se/">https://www.google.se/
https://www.bing.com/">https://www.bing.com/
  • Use code formatting, please: unix.stackexchange.com/editing-help#code – muru Aug 10 at 11:40
  • sed 's/.*/&">&/' 1.txt – Cyrus Aug 10 at 14:18
  • Do you want that in 2.txt because you then have another step afterwards to finally get it into the format you really want in the end? It just looks suspiciously like some intermediate format. – Ed Morton Aug 10 at 23:30
  • How about paste -d "" 2.txt 1.txt -- given your sample files, that's all you need. – glenn jackman Aug 11 at 0:19
2

There does not seem to be any reason to store the data in a variable.

awk -v OFS='">' '{ print $0, $0 }' 1.txt >2.txt

This would do what you seem to want to do, which is to insert the two characters "> at the end of each line, followed by the original contents of the line. In this code, this is done by outputting the line as twe new fields. The output field separator, OFS, will be inserted between these automatically. The value of OFS is set to "> on the command line.

Alternatively, using sed:

sed 's/\(.*\)/\1">\1/' 1.txt >2.txt

This uses a capturing group to capture the whole line. This is then replaced with the captured bit, the string ">, and the captured bit again.

As pointed out in comments, an even shorter variant would be

sed 's/.*/&">&/' 1.txt >2.txt

The &, when it occurs in the replacement part of the s command, will be replaced by the bit of the input matching the expression. The expression is .*, so & would be the complete line, and &">& would insert the line twice with "> in-between.


Your pipeline,

URL=$(grep ".*" ./1.txt) | sed "s/$/\">${URL}/" ./1.txt > ./2.txt

makes little sense, as the left and right hand side of it are executed independently of each other (and there is no communication between them). The value $URL would be empty in the sed expression.

If you had used

URL=$(grep ".*" ./1.txt); sed "s/$/\">${URL}/" ./1.txt >./2.txt

which is the same as

URL=$(<./1.txt); sed "s/$/\">${URL}/" ./1.txt >./2.txt

the sed command would have tried to insert the full contents of the $URL variable (the whole of 1.txt) at the end of each line. It would also have failed, since that value contains several / characters that would have interfered with the / delimiters of the s command.

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.