Search code examples
sedpipels

sed with filename from pipe


In a folder I have many files with several parameters in filenames, e.g (just with one parameter) file_a1.0.txt, file_a1.2.txt etc.
These are generated by a c++ code and I'd need to take the last one (in time) generated. I don't know a priori what will be the value of this parameter when the code is terminated. After that I need to copy the 2nd line of this last file.

To copy the 2nd line of the any file, I know that this sed command works:

sed -n 2p filename

I know also how to find the last generated file:

ls -rtl file_a*.txt | tail -1

Question:

how to combine these two operation? Certainly it is possible to pipe the 2nd operation to that sed operation but I dont know how to include filename from pipe as input to that sed command.


Solution

  • You can use this,

    ls -rt1 file_a*.txt | tail -1 | xargs sed -n '2p'
    

    (OR)

    sed -n '2p' `ls -rt1 file_a*.txt | tail -1`
    
    sed -n '2p' $(ls -rt1 file_a*.txt | tail -1)