-1

I'm unable to remove space from filenames as below, Please advise if any solution is there on this issue. thank you

/home/files:

Dec 14 22:10 testfiles 
Dec 15 12:30 test file1 
Dec 14 21:45 test file2 
Dec 16 02:30 testfile3 
$ ls -lrt| tr -s " "  > filelist.txt 
$ cat filelist.txt 
2022-12-14,testfiles 
2022-12-15,test 
2022-12-14,test 
2022-12-16,testfile3 
kumar
  • 1
  • 2
    Are you actually trying to rename them, or produce a list with them with spaces removed/replaced? Also the command you've included doesn't produce the output you have suggested; not even close. – bxm Dec 21 '22 at 13:35
  • 1
    The ls command that you are using does not provide the output that you present, not Eve when passed through tr like you show. It is unclear whether the exercise is to modify a text file, or whether it to modify some filenames. It is further unclear whether the dates that you show are significant in any way (are they, for example, part of the filenames)? There is also commas introduced in the last shown data, and I don't know where these come from. – Kusalananda Dec 21 '22 at 14:44

2 Answers2

1

Don't parse ls !

If the files exists with dates, and is not just the output of ls -l, you could use Perl's rename:

rename -n -E 's/^(\w+)\s+(\d{2})\s+(\d{2}:\d{2})\s+/$1-$2-$3,/g' -E 's/ //g' Dec*
rename(Dec 14 21:45 test file2 , Dec-14-21:45,testfile2)
rename(Dec 14 22:10 testfiles ,  Dec-14-22:10,testfiles)
rename(Dec 15 12:30 test file1 , Dec-15-12:30,testfile1)
rename(Dec 16 02:30 testfile3 ,  Dec-16-02:30,testfile3)

Remove -n when the output looks satisfactory (dry-run).

  • I wonder whether we should make a "reference" question "Renaming files, represented by a simple replacement or regex", and just make "Perl rename" a canonical answer (also adding the bash/zsh for loop & variable expansion option). OP's question with very little variation is pretty common, isn't it? – Marcus Müller Dec 21 '22 at 12:39
  • 1
    Yes, indeed. I think the linked page is a good reference for perl, zsh and bash renaming – Gilles Quénot Dec 21 '22 at 12:56
  • OK, then I'll just bookmark that and use it as "does this answer your question" going forward. – Marcus Müller Dec 21 '22 at 13:00
0

You would be better not parsing ls at all, but instead just iterating across the files in the directory:

for file in *
do
    ymd=$(date --date "@$(stat -c '%Y' "$file")" +'%Y-%m-%d')
    [ -d "$file" ] && printf "%s,%s\n" "$ymd" "$file"
done

Once you have this loop in place it's trivial to write out file names that omit spaces; just modify the output line:

    [ -d "$file" ] && printf "%s,%s\n" "$ymd" "${file// /}"

Note that per your example this doesn't rename files in the directory, it simply lists them without spaces in the format you've shown in your question.

Chris Davies
  • 116,213
  • 16
  • 160
  • 287