Εμφάνιση αναρτήσεων με ετικέτα line by line ls bash script. Εμφάνιση όλων των αναρτήσεων
Εμφάνιση αναρτήσεων με ετικέτα line by line ls bash script. Εμφάνιση όλων των αναρτήσεων

Τρίτη 15 Ιουλίου 2008

How to get line by line read of "ls" in bash

The problem:

I wanted to write a bash script that will read the output of 'ls' in a directory and rename each file that matched a specific pattern. However I soon found out that using

for line in ls

was no good as it returned the output word by word.

The solution:

The problem was solved after a bit of googling. The code that I needed was:
ls | while read lineVar
do
...
...
done
What this does:

1. ls pipes its output into "while read" which read line by line and stores each line into $lineVar (you don't need the dollar initially).
2. In the while/do loop I can do the pattern matching using sed and renaming.

The full script (currently with no terminal input - it's all hardcoded):
#!/bin/bash

ls | while read lineVar
do
echo OLD: $lineVar
new=`echo $lineVar | sed -e 's/^.....//g'`
echo Replacing $lineVar with $new
mv "$lineVar" "$new"
done
Hope this helps