sed with filename from pipe

14,568

Solution 1

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)

Solution 2

Typically you can put a command in back ticks to put its output at a particular point in another command - so

sed -n 2p `ls -rt name*.txt | tail -1 `

Alternatively - and preferred, because it is easier to nest etc -

sed -n 2p $(ls -rt name*.txt | tail -1)
Share:
14,568
physiker
Author by

physiker

Updated on July 24, 2022

Comments

  • physiker
    physiker almost 2 years

    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.