llancet has asked for the wisdom of the Perl Monks concerning the following question:

It seems to be simple, but I cannot find an way to do that. I have several tab-delimited files in one folder. I want to merge them into one file, and add a new column for file name.

For example, input files are:
file "A.tab":

XXX XXX XXX XXX XXX XXX
file "B.tab":
XXX XXX XXX XXX XXX XXX
expected output:
A.tab XXX XXX XXX A.tab XXX XXX XXX B.tab XXX XXX XXX B.tab XXX XXX XXX

I firstly tried to use something like this:

for file in `ls my_input_dir`; do perl -n -E 'print "$ARGV[0]\t$_"' my +_input_dir/$file; done
but it won't work, as the file name is not got in $ARGV...

Replies are listed 'Best First'.
Re: How to do this with shell scripting and perl one-line?
by BrowserUk (Patriarch) on Dec 29, 2011 at 11:06 UTC

    Instead $ARGV[0], you could use just $ARGV which will be the name of the file being read by -n. The problem is it will contain the full path.

    If you don't want that in the file, cd to the directory first and supply just the filename to perl.


    With the rise and rise of 'Social' network sites: 'Computers are making people easier to use everyday'
    Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
    "Science is about questioning the status quo. Questioning authority".
    In the absence of evidence, opinion is indistinguishable from prejudice.

    The start of some sanity?

Re: How to do this with shell scripting and perl one-line?
by JavaFan (Canon) on Dec 29, 2011 at 11:22 UTC
    I'd use the shell:
    grep -H "" `ls my_input_dir` | sed -s s/:/ /'
    This is for GNU grep. I vaguely remember having some minor portability issue back in the 1990s related to an -H option, but my memory is unclear whether that was with grep or find. (I was porting a 1500 line shell/AWK/SQL script I wrote for Solaris 2.4 to HP-UX and Windows NT, with the -H thingy the only fix needed to get it running on HP-UX (and no fix needed to make it run on Windows NT))
Re: How to do this with shell scripting and perl one-line?
by choroba (Cardinal) on Dec 29, 2011 at 11:07 UTC
    the file name is not got in $ARGV
    In fact, it is not in @ARGV, but it is in $ARGV. See perlvar.
Re: How to do this with shell scripting and perl one-line?
by hbm (Hermit) on Dec 29, 2011 at 15:05 UTC
    (cd /my/input/dir;(perl -pe'print"$ARGV\t"' *.tab)>combo.tab)