I have a file (say called list.txt
) that contains relative paths to files, one path per line, i.e. something like this:
foo/bar/file1
foo/bar/ba
Here is one example to find and replace file extensions to xml.
for files in $(ls); do
filelist=$(echo $files |cut -f 1 -d ".");
mv $files $filelist.xml;
done
Great solution from this source
p=/foo/bar/file1
path=$( echo ${p%/*} )
file=$( echo ${p##/*/} )
This also works with spaces in the path!
Use basename
and dirname
, that's all you need.
part1=`dirname "$p"`
part2=`basename "$p"`
A proper 100% bash way and which is safe regarding filenames that have spaces or funny symbols (provided inner_process.sh
handles them correctly, but that's another story):
while read -r p; do
[[ "$p" == */* ]] || p="./$p"
inner_process.sh "${p%/*}" "${p##*/}"
done < list.txt
and it doesn't fork dirname
and basename
(in subshells) for each file.
The line [[ "$p" == */* ]] || p="./$p"
is here just in case $p
doesn't contain any slash, then it prepends ./
to it.
See the Shell Parameter Expansion section in the Bash Reference Manual for more info on the %
and ##
symbols.