Hi All,
Have a file where i stored ls -l command output,
-rw-r--r-- 1 360 600 94255 Jan 01 11:16 file1_2020.csv
-rw-r--r-- 1 360 600 114573 Dec 29 11:10 file2_2019.csv
-rw-r--r-- 1 360 600 41006 Dec 30 11:09 file3_2019.csv
-rw-r--r-- 1 360 600 165923 Dec 31 11:29 file4_2019.csv
Want to extract year from filename and insert in every respective line, output should be:
-rw-r--r-- 1 360 600 94255 Jan 01 11:16 2020 file1_2020.csv
-rw-r--r-- 1 360 600 114573 Dec 29 11:10 2019 file2_2019.csv
-rw-r--r-- 1 360 600 41006 Dec 30 11:09 2019 file3_2019.csv
-rw-r--r-- 1 360 600 165923 Dec 31 11:29 2019 file4_2019.csv
Can this be possible using awk and sed in one line instead of running any for loop.
**I got this output from ftp server, and that is why cannot use ls --fu command to get year. That is why i thought of appending year after getting filenames to local server, If there is any alternative for this kindly let me know
Thank you for your suggestion, Yes i have save my output of ls command in file. and Can you please explain little bit in detail what we are doing in this solution.
Also what if my input is:
-rw-r--r-- 1 360 600 165923 Dec 31 11:29 12312019 file1_12312019_062449.csv
How can i extract year part in same solution, tried but could not get the expceted.
use time-style=+FORMAT to force a constant time format on ls -l output, +FORMAT uses the format that the date command uses as well.
See the man page for your date command if this is foreign to you.
Example:
# set time to exactly right now on the t.lis file
touch t.lis
ls -l --time-style='+%Y-%m-%d %H:%m' t.lis
-rw-r--r-- 1 Owner None 1055 2020-01-02 16:01 t.lis
awk ' ##starting awk program from here.
{
split($NF,array,"[_.]") ##Using split to splitting the last field of current line into an array named array with field separator of underscore and dot.
$NF=array[2] OFS $NF ##resetting last field value with 2nd value of array(which was year value) OFS and last field value itself.
}
1 ##Mentioning 1 will print edited/non-edited lines here.
' Input_file ##Mentioning Input_file name here.
Thanks for your reply, and yes i am well aware about DATE command and its relevant formats, kindly follow my first post carefully as i mentioned that i cannot use any ls options because i am getting file listing from ftp server. Is there any command which can give me desired result directly from ftp while using ls?
For Thanking someone on Unix.com you could HIT THANKS button at the left corner of each post.
For your other question in your previous post, I believe my same command should work, though I made a small change in it, try following and let me know then.
-rw-r--r-- 1 360 600 165923 Dec 31 11:29 12312019 file1_12312019_062449.csv
and the awk command will extract whole set of string i.e "12312019" for $NF=array[2], rather i need this substr(5:8) i.e. "2019" . In my earlier input i had only 2019 as second field but in this ihave date and month too. So i am not getting how to extract last 4 chars from array[2].