Add text at start and ending of every line

Hi all,

Is there other way to Add text at start and ending of every line?

here my script:

cat file.txt |awk '{print "<p align=\"justify\">"$0"</p>"}'

but the problem they put including white spaces, I only need those line have a sentence or text not an skip all have empty string or have a white space

Hello lxdorney,

If I understood correctly you need to skip those lines which are empty, then you can try following. It is good you are showing us what you have tried so far, please try to add your input file and expected output too. Will be helpful for us.

 awk '($0 !~ /^$/){print "<p align=\"justify\"> " $0 " </p>"}'  Input_file
 

Thanks,
R. Singh

1 Like

If you want to exclude lines containing <TAB>s and spaces as well, try

awk '!/^[\t ]*$/ {print "<p align=\"justify\"> " $0 " </p>"}'  file
1 Like

The following takes advantage of awk's autosplit on whitespace.

awk 'NF {print "<p align=\"justify\"> " $0 " </p>"}' file.txt

If you want to keep the blank lines:

awk 'NF {$0 = "<p align=\"justify\"> " $0 " </p>"} {print}' file.txt
1 Like

You don't need to use cat. Awk can read files on its own.

Here's another way without Awk.

 perl -nle 'print "<p align=\"justify\">$_</p>" unless /^$/' file.txt
1 Like

Thanks for the help,

I tried above scripts but the output is all same

<p align="justify">^M</p>
<p align="justify">^M</p>
<p align="justify">^M</p>
<p align="justify">^M</p>
<p align="justify">^M</p>
<p align="justify">^M</p>
<p align="justify"> Hello World ^M</p>
<p align="justify">^M</p>
<p align="justify">^M</p>
<p align="justify">^M</p>
<p align="justify">Hello World1^M</p>
<p align="justify">^M</p>
<p align="justify">Hello World2^M</p>
<p align="justify">^M</p>
<p align="justify">^M</p>
<p align="justify">^M</p>
<p align="justify">Hello World3^M</p>
<p align="justify">^M</p>
<p align="justify">^M</p>

I have a text file:

#cat text.txt





Hello World



Hello World1

Hello World2



Hello World3

and heres what I want to Achieve:





<p align="justify"> Hello World</p>



<p align="justify">Hello World1</p>

<p align="justify">Hello World2</p>



<p align="justify">Hello World3</p>

you've a DOS formatted file then. first convert it to unix, or amend the script like so:

awk '{sub(/\r$/,"")}NF {print "<p align=\"justify\"> " $0 " </p>"}' file.txt
1 Like

Thanks so much guys