0

Input:

Col1 col2 col3 col4
aaa   15   23   A
bbb    7    5   B
ccc   43   10   C

Expected output

aaa  15  16
bbb   7   8
ccc  43  44

I know to get this using awk but I need to do this in Perl. I tried using an array in Perl like

 push(@output_array, $temp_array[0] . "\t" . $temp_array[1] .  "\n");

I don't know how to add 1 to the col2 and make it as col3. Can anybody help me out?

1
  • 1
    There's a program that's been distributed with Perl since forever called a2p for converting awk scripts to Perl. (There's also an s2p for converting sed scripts to Perl.) Maybe that would help? Commented May 12, 2014 at 4:17

2 Answers 2

4

In a perl oneliner

perl -lane 'print join("\t", @F[0,1], $F[1] + 1)' file.txt

If you want to truncate a header row:

perl -lane 'print join("\t", @F[0,1], $. == 1 ? $F[2] : $F[1] + 1)' file.txt

If you want to completely remove a header row:

perl -lane 'print join("\t", @F[0,1], $F[1] + 1) if $. > 1' file.txt
Sign up to request clarification or add additional context in comments.

5 Comments

can you help me on how to do that using array?
@F its an array. Gets invoked by using the "-a" command line switch. perldoc perlrun
@Miller, the second one liner is not removing the header
@sara: it isn't trying to remove the header; it is echoing it with the heading of column 3 unchanged. If you don't want the first line printed, then add if $. > 1 between the close parenthesis and single quote of the first script.
@sara Added 3rd option for completely removing a header row instead of just truncating.
0
push(@output_array, $temp_array[0] . "\t" , $temp_array[1] . "\t" , $temp_array[1] + 1 . "\n");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.