Leon
Leon

Reputation: 468

How to show the specific columns which separated by one to more spaces using BASH commands?

I have different data which were created at different date and time shown below.

-rw-rw-r-- 1 user user 157559823 May 23  09:39 1x100.lammpstrj
-rw-rw-r-- 1 user user 157560063 Jul  2  08:22 2x200.lammpstrj
-rw-rw-r-- 1 user user 157561559 Jul  7  13:13 3x250.lammpstrj
-rw-rw-r-- 1 user user 157560934 Jul  9  10:10 4x300.lammpstrj
-rw-rw-r-- 1 user user 157566774 Jul 19  11:29 5x350.lammpstrj

I hope to show the last column which are file names with suffix .lammpstrj. If I use

`ls -latr *.lammpstrj | cut -d ' ' -f 9`

I cannot get all file names. I noticed that the multiple spaces between month and day led to such problems. Any universal solution for cases similar to this one? I sincerely appreciate your time and help.

Upvotes: 1

Views: 48

Answers (2)

dstandish
dstandish

Reputation: 2408

If you're just after the filenames, using find will get you there:

find *.lammpstrj -maxdepth 1 -type f

Upvotes: 1

glenn jackman
glenn jackman

Reputation: 247210

If you just want to view them: ls -1 *.lammpstrj

If you want to iterate over them: for file in *.lammpstrj; do ...

If you want to store them for later use:

files=(*.lammpstrj)
# now do stuff with them, for example print them:
printf "%s\n" "${files[@]}"
# or something else
for file in "${files[@]}"; do ...

To get metadata about your files, use stat:

stat -c "%Y %s %n" *.lammpstrj | while read -r mtime size filename; do
    printf "%s has size %d and was last modified %s\n" \
      "$filename" \
      "$size" \
      "$(date -d "@$mtime" "+%Y-%m-%d %H:%M:%S")"
done

Or use -printf in find

Upvotes: 1

Related Questions