Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sed with filename from pipe

Tags:

sed

pipe

ls

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.

like image 583
physiker Avatar asked Feb 18 '14 12:02

physiker


People also ask

Can you pipe to sed?

Since sed can read an input stream, CLI tools can pipe data to it. Similarly, since sed writes to stdout, it can pipe its output to other commands.

How do you use sed and cat together?

You can cat the file sample. txt and use the pipe to redirect its output (the lines of text) into the sed command. The -e option to sed tells it to use the next item as the sed command. The d command tells sed to delete lines 1–15 of the input stream, which in this case is the lines read from sample.

How do you use sed command to replace a string in a file?

Find and replace text within a file using sed command Use Stream EDitor (sed) as follows: sed -i 's/old-text/new-text/g' input.txt. The s is the substitute command of sed for find and replace. It tells sed to find all occurrences of 'old-text' and replace with 'new-text' in a file named input.txt.

Does sed output to stdout?

The output is displayed on stdout.


2 Answers

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)
like image 88
sat Avatar answered Sep 20 '22 06:09

sat


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)
like image 20
Floris Avatar answered Sep 20 '22 06:09

Floris