Insert string in alternate lines

Hi All,

In continuation of my previous thread 'Add text at the end of line conditionally', I need to further modfiy the file after adding text at the end of the line. Now, I need to add a fixed charater string at alternate lines starting from first line using awk or sed.My file is now as below:

cat myfile

aaaa.txt
bbbb.txt
cccc.txt

VAR="This is a new file"
I have the string stored in the variable VAR and I need the output as below:

cat myfile

This is a new file
aaaa.txt
This is a new file
bbbb.txt
This is a new file
cccc.txt

Regards
Angshuman

Try:

sed "s/^/$VAR\n/" file

Hi Scrutinizer,

It is inserting the value but not adding a new line. Actually, I tried this earlier also but it did not work. Here is what I did:

sed "s/^/$VAR\n/" myfile >tempfile.txt
mv tempfile.txt myfile

cat myfile

This is a new filenaaaa.txt
This is a new filenbbbb.txt
This is a new filencccc.txt

Regards
Angshuman

awk -vvar=$VAR '{print var;print $0}' file
1 Like

@angshuman. Are you on Solaris? Use /usr/xpg4/bin/sed instead of sed.

Hi Scrutinizer,
I am on HP Unix
Regards
Angshuman

You probably need to use an actual linefeed character:

sed "s/^/$VAR^M/" myfile >tempfile.txt

^M is entered as CTRL-V <ENTER>

I tried this (used actual linefeed by pressing CTRL-V + Enter key) but still no luck. This time the output is as below:

This is a new line^Maaaa.txt
This is a new line^Mbbbb.txt
This is a new line^Mcccc.txt

I tried the solution provided by ghostdog74 and got the following error message:

awk: Cannot find or open file a.
The source line number is 1.

cat myfile

aaaa.txt
bbbb.txt
cccc.txt

Regards
Angshuman

Yeah that won't work... Try this then:

sed "i\
$VAR" file

Or try ghostdogs' suggestion with double quotes:

awk -vvar="$VAR" '{print var;print $0}' infile
1 Like

Hi All,

Thanks for the help. I used ghostdog's solution and it worked perfectly.

Scrutinizer,

I still had problem when i used your solution. This time I got the following error:

sed: Function i cannot be parsed.

However, thanks for your time and help

Regards
Angsuman

Good. Regarding the sed suggestion: there should be no spaces behind the \