UNIX trick or command

Hi,

Is there any command to do this --

Input is --

Ant
Bat
Cat
Dog

Output is --

A_Ant
B_Ant
A_Bat
B_Bat
A_Cat
B_Cat
A_Dog
B_Dog

Thanks

Hello Indra2011,

Could you please try following and let me know if this helps you.

awk '{print "A_" $0 ORS "B_" $0}'  Input_file

Thanks,
R. Singh

1 Like

Shell:

while read line; do
  for i in A B; do
    echo "${i}_${line}"
  done
done < infile
1 Like

Thanks both of you. It worked .I wonder things are so simple for you guys

Hello Scrutinizer,

Just for fun, we could remove 1 loop from above code and could try following.

while read line
do
    echo -e "A_$line\nB_$line";
done < "Input_file"
 

Thanks,
R. Singh

Indeed Ravinder.
One note: the portable (Posix) way of doing this would be:

printf "A_%s\nB_%s\n" "$line" "$line"

And printf is even portable to awk

awk '{printf "A_%s\nB_%s\n", $0, $0}' Input_file

---------- Post updated at 16:56 ---------- Previous update was at 16:27 ----------

A sed multi-liner

sed '
s/.*/A_&\
B_&/
' Input_file

Just for the fun of it - might make me eligible for some "science of stupid award"...

paste -d"A_\nB_" /dev/null /dev/null file /dev/null /dev/null file
A_Ant
B_Ant
A_Bat
B_Bat
A_Cat
B_Cat
A_Dog
B_Dog
2 Likes

You'll get my recommendation :wink: You know I love these :slight_smile: .

It could be shortened a little still::

paste -d"A_\nB_" - - file - - file </dev/null
1 Like

Why am I always late to this kind of thing?

while read line
do
   printf "%s\n" {A_,B_}$line
done

Nice, but please add quotes around variables in command arguments!

while read line; do printf "%s\n" {A_,B_}"$line"; done < file

You're right, of course. I forgot them in my haste to post that suggestion.

Andrew

Another sed -solution:

sed 's/^/A_/p;s/^./B/' file

I hope this helps.

bakunin

1 Like