sed with listing

Hi,

I would like to get latest file with using listing tail and want to replace header's first column starting from # to nothing.

I am using this to replace first header #

code :-

sed '1s/#//'

but I want to do something like this.

Code :-

ls promo_random.csv | tail -1 |  sed '1s/#//'

Output :-

promo_random.csv

Output should be the replacement of # of last file from listing.

Do you mean that you want to read the file's content rather than just the name?

Perhaps this might help:

sed '1s/#//' promo_random.csv

Does that help, or have I missed the point? It would help if you can explain a little more, preferably with the output you are getting, sample data from your file and the desired output. Please wrap all code, files, input & output/errors in CODE tags. Highlight the text required and press the button on the toolbar which has co over de. You can check and adjust it by pressing the Go Advanced button below.

Kind regards,
Robin

Suppose, I have 2 files in directory

ls promo_random*.csv

Result:-

promo_random_20180401.csv
promo_random_20180501.csv

I want to pick last file which is latest and use as an input for sed command to replace# in that file

Okay, that is possible. I'm assuming that the filename contains the date & time in a sorted format, do these are 1st April and 1st May. Does this help:-

sed '1s/#//' $(ls promo_random_*.csv | tail -1)

An alternate might be:-

for testfile in promo_random_*.csv
do
   sedfile="${testfile}"                                  # Remember this filename
done

[ ! -z "${sedfile} ] && sed '1s/#//' "${sedfile}"         # If the value of sedfile is not null, process it

You can argue that the first one spawns another few processes to run the ls & the tail so might be slower, but it's obviously more compact. I suppose it depends on the size of the list. It is probably negligible in most cases. If you are going to reprocess a large list, then it would probably be better to store it rather than to keep re-reading it.

Does that help?

Do you want the output to the screen (STDOUT) another file, or to update the file?

Robin

ls has a reverse option, of course, allowing one to ues head :

sed '1s/#//' $(ls -r promo_random_*.csv | head -1)

This may be quicker if you have a large number of files.

Andrew