Sunday, May 29, 2011

removing newline character in shell and perl


 To my knowledge there are two ways to remove "\n" in shell:

1)using formatted printing in awk
2)using truncate(tr) option in shell


This can be further clarified by the below example:


acer@ubuntu:~$ echo "hello"
hello
acer@ubuntu:~$ echo "hello" | awk '{printf ("%s",$1) }'
helloacer@ubuntu:~$ echo "hello" | tr -d "\n"
helloacer@ubuntu:~$

As you may see in the first case there is a default "\n" with echo
But in the second and third case it is removed using the above said methods.


In perl to remove the "\n" we have a separate function chomp:

The way to use the function in perl is


acer@ubuntu:~$ cat kar.pl
#/usr/bin/perl
$dd="hello\n";
chomp($dd);
print "$dd";
acer@ubuntu:~$ perl kar.pl
helloacer@ubuntu:~$