-
Notifications
You must be signed in to change notification settings - Fork 0
/
add_column_with_filename.pl
91 lines (70 loc) · 1.7 KB
/
add_column_with_filename.pl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
#!/usr/bin/env perl
# Adds column with table filename in all values.
# Usage:
# perl add_column_with_filename.pl [table to add column to]
# Prints to console. To print to file, use
# perl add_column_with_filename.pl [table to add column to] > [output table path]
use strict;
use warnings;
my $table = $ARGV[0];
my $REMOVE_ALL_FILE_EXTENSIONS = 1;
my $NEWLINE = "\n";
my $DELIMITER = "\t";
# verifies that input table exists and is not empty
if(!$table or !-e $table or -z $table)
{
print STDERR "Error: table to add column to not provided, does not exist, or empty:\n\t"
.$table."\nExiting.\n";
die;
}
# retrieve table file name from table file path
my $table_filename = $table;
if($table_filename =~ /^.*\/(.*)$/) # remove directory path
{
$table_filename = $1;
}
if($table_filename =~ /^(.*)[.].*$/) # remove file extension
{
$table_filename = $1;
}
if($REMOVE_ALL_FILE_EXTENSIONS)
{
while($table_filename =~ /^(.*)[.].*$/) # remove file extension
{
$table_filename = $1;
}
}
# reads in and adds column to table to add columns to
my $first_line = 1;
open TABLE, "<$table" || die "Could not open $table to read; terminating =(\n";
while(<TABLE>) # for each row in the file
{
chomp;
my $line = $_;
if($line =~ /\S/) # if row not empty
{
if($first_line) # column titles
{
# prints line as is
print $line;
# prints title of new column
print $DELIMITER;
print "filename";
print $NEWLINE;
$first_line = 0;
}
else # column values (not column titles)
{
# prints line as is
print $line;
# prints value of new column
print $DELIMITER;
print $table_filename;
print $NEWLINE;
}
}
}
close TABLE;
# September 26, 2021
# November 8, 2021
# June 9, 2023